目前我正在尝试一段代码,其基本功能如下:
void f(int x) { cout << "f("<<x<<")" << endl; }
class C
{
public:
void m(int x) { cout << "C::m("<<x<<")" << endl; }
};
class C2
{
public:
void registerCallback(function<void(int)> f)
{
v.push_back(f);
}
private:
vector<function<void(int)>> v;
void callThem()
{
for (int i=0; i<v.size(); i++)
{
v[i](i);
}
}
};
int main()
{
C2 registrar;
C c;
registrar.registerCallback(&f); // Static function
registrar.registerCallback(bind(&C::m, &c, placeholders::_1)); // Method
return 0;
}
这个方案相当不错。但是我在这个模式上遇到了困难。我想检查回调是否已经注册,并且我想通过将其从向量中移除来取消注册回调。我刚学会了,
std::function
对象无法进行比较,这意味着无法在容器中搜索它们的存在。所以我需要一种替代方案。当然,我希望保持编译时类型检查和注册任意类方法的能力。
如何实现类似的解决方案,允许取消注册回调和检查双重注册?我需要接受哪些权衡?