Can we increase the re-usability for this key-oriented access-protection pattern:
class SomeKey {
friend class Foo;
// more friends... ?
SomeKey() {}
// possibly non-copyable too
};
class Bar {
public:
void protectedMethod(SomeKey); // only friends of SomeKey have access
};
To avoid continued misunderstandings, this pattern is different from the Attorney-Client idiom:
- It can be more concise than Attorney-Client (as it doesn’t involve proxying through a third class)
- It can allow delegation of access rights
- … but its also more intrusive on the original class (one dummy parameter per method)
(A side-discussion developed in this question, thus i’m opening this question.)
I like this idiom, and it has the potential to become much cleaner and more expressive.
In standard C++03, I think the following way is the easiest to use and most generic. (Not too much of an improvement, though. Mostly saves on repeating yourself.) Because template parameters cannot be friends, we have to use a macro to define passkey’s:
This method has two drawbacks: 1) the caller has to know the specific passkey it needs to create. While a simple naming scheme (
function_key) basically eliminates it, it could still be one abstraction cleaner (and easier). 2) While it’s not very difficult to use the macro can be seen as a bit ugly, requiring a block of passkey-definitions. However, improvements to these drawbacks cannot be made in C++03.In C++0x, the idiom can reach its simplest and most expressive form. This is due to both variadic templates and allowing template parameters to be friends. (Note that MSVC pre-2010 allows template friend specifiers as an extension; therefore one can simulate this solution):
Note with just the boilerplate code, in most cases (all non-function cases!) nothing more ever needs to be specially defined. This code generically and simply implements the idiom for any combination of classes and functions.
The caller doesn’t need to try to create or remember a passkey specific to the function. Rather, each class now has its own unique passkey and the function simply chooses which passkey’s it will allow in the template parameters of the passkey parameter (no extra definitions required); this eliminates both drawbacks. The caller just creates its own passkey and calls with that, and doesn’t need to worry about anything else.