派生类不调用基类的成员函数

时间:2014-09-25 08:11:14

标签: c++ templates inheritance multiple-inheritance c++14

说我有一个类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);

...未调用连接函数!

这使我相信operator()中定义的event_callable未正确调用,或vector m_funcs未在方法中遍历。< / p>

我在这里做错了什么和/或为什么vector没有被迭代过来?

1 个答案:

答案 0 :(得分:3)

你有一个菱形的继承,这意味着在你的情况下,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 { ... };