Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern:
class SomeKey { friend class Foo; SomeKey() {} // possibly make it non-copyable too }; class Bar { public: void protectedMethod(SomeKey); };
Here only a friend
of the key class has access to 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 } };
It allows more fine-granular access-control than making Foo
a friend
of Bar
and avoids more complicated proxying patterns.
Does anyone know whether this approach already has a name, i.e., is a known pattern?
Thanks to your other question it looks like this pattern is now known as the "passkey" pattern.
In C++11, it gets even cleaner, because instead of calling
b.protectedMethod(SomeKey());
you can just call:
b.protectedMethod({});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With