【问题标题】:Restricting methods to only few classes in c++将方法限制为 c++ 中的几个类
【发布时间】:2013-04-12 22:00:42
【问题描述】:

我有一个通知类,它的界面类似于以下(有一些语法问题):

template<typename ...T>
Notification
{

public:
void addObserver(std::function<void (T...)> o);
void notify(T...);
};

然后有一个主机类充当通知中心:

class NotificationCenter
{

public:
    Notification<int, int> mPointChangedNotification;
};

最后,还有实际的观察者来监听通知:

class Listener
{
void someFunction(int, int)
{
}

void SomeMethod(NotificationCenter &m)
{
m.mPointChangedNotification.addObserver(someFunction);
}
};

所以,到目前为止一切顺利。但问题是即使实际观察者也可以看到 notify 函数,而它应该只能由 NotificationCenter 类访问。如果有人可以帮助解决这个设计问题,那将非常有帮助。

提前致谢。

【问题讨论】:

    标签: c++ templates c++11


    【解决方案1】:

    如果您在设计访问控制策略时不需要太大的灵活性,您可以简单地将 NotificationCenter 设为 friendNotification 类模板(同样,提供 notify() 私有可访问性):

    template<typename ...T>
    Notification
    {
    public:
        void addObserver(std::function<void (T...)> o);
    private:
        friend class NotificationCenter;
        void notify(T...);
    };
    

    这样,NotificationCenter 将被允许调用notify(),但所有其他客户端只能访问addObserver()


    如果您想获得更大的灵活性,您可以让Notification 接受另一个模板参数,并将该模板参数中指定的类型设为friendNotification。然后,您可以赋予notify() 私有可访问性,这样其他非friend 类将无法调用它:

    template<typename F, typename ...T>
    Notification
    {
    public:
        void addObserver(std::function<void (T...)> o);
    private:
        friend class F;
    //  ^^^^^^^^^^^^^^^
        void notify(T...);
    };
    

    【讨论】:

    • 非常感谢!但是如果让整个 NotificationCenter 成为 Notification 的好友,那么 NotificationCenter 就可以访问 Notification 的所有私有数据。那么,有没有办法限制它的成员?
    • @Aarkan:是的,这是可能的。见here。在该示例中,我只创建了BfriendA 的两个成员函数之一,如果非friend 函数试图访问A 的函数,编译器将生成错误私人会员
    猜你喜欢
    • 2023-03-06
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2019-11-21
    相关资源
    最近更新 更多