在c++中将方法限制在几个类中
Restricting methods to only few classes in c++
我有一个通知类,它的接口类似于以下(有一些语法问题):
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
接受另一个模板参数,并使该模板参数中指定的类型为Notification
的friend
。然后,您可以为notify()
提供私有可访问性,这样其他非friend
类将无法调用它:
template<typename F, typename ...T>
Notification
{
public:
void addObserver(std::function<void (T...)> o);
private:
friend class F;
// ^^^^^^^^^^^^^^^
void notify(T...);
};
相关文章:
- 为我的 c++ 类介绍制作一个三角形分类器.我有几个问题
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 如何返回或护理项目清单基于几个类别
- 我们如何在文本文件中找到C++中的几个单词?
- 关于 std::bitset 构造函数的几个问题?
- 几个 Nt 函数在 Windows 7 x32 上返回STATUS_WAIT_0
- std::stoi 只转换前几个字符
- C++ 通过接口使用从其他几个类继承的类
- 在矢量中使用擦除时双重释放或损坏(快速顶部).如何擦除一个矢量的几个项目知道它们的索引?
- 如何遍历几个每小时一次的根(.root)文件,并将它们组合成更大的每日数据.root文件?
- 我有几个关于参考变量的问题
- 如何将几个变量复制到其他变量
- 如何在新设计中迁移需要几个额外参数的函数
- 多线程.如果我使用信号量,我可以在开始时创建很多线程还是应该只有几个线程?
- 如何在几个空行后打印文件中的输出
- recvfrom 只收到几个数据包,之后它进入等待状态
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- C++ 两个线程,共享几个整数变量
- 在循环中使用字符串流从几个字符串中提取数字
- 哪个链接更快?许多小的 .so 文件还是几个大的 .so 文件?