C++, using a key class as a key of access for a gr

2019-08-03 11:00发布

问题:

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?