问题
I've seen a pattern like this in some project:
class AccessKey{
// a group of classes called privilegedClasses
friend class foo;
friend class bar;
// friend class other classes in privilegedClasses...
private :
AccessKey(){}; /*! private constructor */
static const AccessKey key; /*! private object, only for friend classes */
}
This is a class that only privilegedClasses can access to it and have an object of it. Now consider someone is writing a function and want to limit access to that function to classes in privilegedClasses. She can do it simply by adding an AccessKey object to arguments. like this:
void functionForPrivilegedClassses(AccessToken token, ...){
}
Therefore only classes in privilegedClasses can call this function because only they can have an object of that class.
Invocation would be like this: functionForPrivilegedClasses(AccessKey::key,...)
I want to know is it a good practice generally? Is there a better way to achieve this?
来源:https://stackoverflow.com/questions/23993264/c-using-a-key-class-as-a-key-of-access-for-a-group-of-classes