在c++中将方法限制在几个类中

Restricting methods to only few classes in c++

本文关键字:几个 c++ 方法      更新时间:2023-10-16

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

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类才能访问。如果有人能提供帮助来解决这个设计问题,那将是非常有帮助的。

如果您在设计访问控制策略时不需要太多的灵活性,您可以简单地将NotificationCenter设置为Notification类模板的friend(再次给予notify()私有访问权限):

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

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


如果您希望允许更大的灵活性,您可以让Notification接受另一个模板参数,并使该模板参数中指定的类型为Notificationfriend。然后,您可以为notify()提供私有可访问性,这样其他非friend类将无法调用它:

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