我有一个带有方法模板的类:
struct Subject
{
template <typename T>
void doSomething()
{
..
}
};
现在,每当调用 doSomething
时(使用任何 T
),我希望通知“观察者”:
template <typename T>
void onDoSomething()
{
..
}
观察者是一个方法模板(包含方法的类模板也可以),这一点很重要。如果不是,我可以实现通用观察者模式。
修改Subject::doSomething()
以便它调用一个方法就可以了。然而,类Subject
不应该“知道”具体的Observer/观察者方法。
这背后的想法是:我在两个项目中使用Subject
。我只需要(并且拥有)其中一个观察者。
有什么办法可以实现这一点吗?
最佳答案
艰难的一个。看来归结为
Notification must be resolvable at compile time (it's a template)
同时,
The notification should not be resolvable at compile time (
Subject
shouldn't know the observer)
我可以想到两种方法:
1.
添加 doSomething
的重载:
template <typename T, typename Observer>
void doSomething()
{
doSomething<T>();
Observer::onDoSomething<T>();
}
然后在项目A中调用单参数版本,在项目B中调用双参数版本。
2.
让定义 Subject
的文件包含一个 header ,该 header 在每个项目中都有不同/不同的配置:
主题.h
#include "observer_def.hpp"
struct Subject
{
template <typename T>
void doSomething()
{
..
notifyDoSomething<T>();
}
};
项目A中的observer_def.hpp:
template <typename>
inline void notifyDoSomething() {}
项目B中的observer_def.hpp:
template <typename T>
inline void notifyDoSomething()
{
MyObserver::onDoSomething<T>();
}
关于c++ - 实现 "static observer pattern",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15807886/