假设我有一个像这样定义的类 event_base
template<typename ... Args>
class event_base{
public:
using delegate_type = std::function<void(Args...)>;
using id_type = size_t;
protected:
std::vector<std::tuple<delegate_type, id_type>> m_funcs;
};
然后我有一些基于事件是否可变和/或可调用的派生类
可变的:
template<typename ... Args>
class event_mutable: public event_base<Args...>{
public:
using id_type = typename event_base<Args...>::id_type;
template<FunctorType>
id_type connect(FunctorType &&f){
this->m_funcs.emplace_back(f, ++m_last_id);
return m_last_id;
}
bool disconnect(id_type id){
for(auto iter = begin(this->m_funcs); iter != end(this->m_funcs); ++iter)
if(std::get<1>(*iter) == id){
this->m_funcs.erase(iter);
return true;
}
return false;
}
};
可调用:
template<typename ... Args>
class event_callable: public event_base<Args...>{
public:
void operator()(Args ... args) const{
for(auto iter = this->m_funcs.rbegin(); iter != this->m_funcs.rend(); ++iter)
(std::get<0>(*this))(args...);
}
};
对于两者:
template<typename ... Args>
class event: public event_mutable<Args...>, public event_callable<Args...>{};
类型之间的转换工作正常,但出于某种原因,当我调用这样的事件时......
event<int> int_ev;
int_ev.connect(/* ... some function ... */);
int_ev(5);
...未调用连接的函数!
这让我相信 event_callable
中定义的 operator()
没有被正确调用,或者 vector
m_funcs
未在方法内遍历。
我在这里做错了什么和/或为什么 vector
没有被迭代?
最佳答案
您有一个菱形继承,这意味着在您的情况下,event
获得了两个版本的m_funcs
;一个来自 event_mutable
,一个来自 event_callable
。因此,connect()
填充 event_mutable::m_funcs
,operator()
在 event_callable::m_funcs
中搜索。您应该使用虚拟继承来克服这个问题:
class event_callable: public virtual event_base { ... };
class event_mutable: public virtual event_base { ... };
class event: public event_callable, public event_mutable { ... };
关于c++ - 派生类不调用基类的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26033614/