Matthieu M.在我以前见过的这个答案中提出了一种访问保护模式,但从未有意识地考虑过一种模式:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
这里只有一个friend
关键类可以访问protectedMethod()
:
class Foo {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
}
};
class Baz {
void do_stuff(Bar& b) {
b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
}
};
Foo
它允许比制作更细粒度的访问控制friend
并Bar
避免更复杂的代理模式。
有谁知道这种方法是否已经有了名字,即,是一种已知的模式吗?