将方法限制为只有几个c ++类

时间:2013-04-12 13:51:36

标签: c++ templates c++11

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

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);
}
};

所以,非常好。但问题是即使对于实际的观察者来说,通知功能也是可见的,而它只能由NotificationCenter类访问。如果有人可以提供帮助来解决这个设计问题,那将非常有用。

提前致谢。

1 个答案:

答案 0 :(得分:3)

如果您在设计访问控制政策时不需要太多灵活性,则只需NotificationCenter friend Notificationnotify()类模板(再次授予{{} 1}}私人辅助功能):

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

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


如果您希望获得更大的灵活性,可以让Notification接受更多模板参数,并使该模板参数中指定的类型为friend Notification。然后,您可以授予notify()私有辅助功能,以便其他非friend类无法调用它:

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