C++, using a key class as a key of access for a group of classes

扶醉桌前 提交于 2019-12-24 10:38:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!