Matthieu M.在我之前看过的这个答案中提出了一种访问保护模式,但从未有意识地考虑过一种模式:
class SomeKey {
friend class Foo;
SomeKey() {}
// possibly make it non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey);
};
Run Code Online (Sandbox Code Playgroud)
这里只有一个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
}
};
Run Code Online (Sandbox Code Playgroud)
它允许更多的细粒度访问控制不是制造Foo一个friend的Bar,避免了更复杂的代理模式.
有谁知道这种方法是否已经有一个名称,即,是一个已知的模式?