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

标签 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);

...未调用连接的函数!

这让我相信 event_callable 中定义的 operator() 没有被正确调用,或者 vector m_funcs 未在方法内遍历。

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

最佳答案

您有一个菱形继承,这意味着在您的情况下,event 获得了两个版本的m_funcs;一个来自 event_mutable,一个来自 event_callable。因此,connect() 填充 event_mutable::m_funcsoperator()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/

相关文章:

c++ - Qt + OpenCV灰度错误

c++ - T、volatile T 和 std::atomic<T> 之间有什么区别?

c++ - 在每个源文件中替代 "extern template"

Android:创建父布局并扩展它以在应用程序的所有 Activity 中保持相同的外观

Ruby 类变量

c++ - Visual Studio 编译器错误 : a call to a delegating constructor shall be the only member-initializer

c++ - 当 T 不可移动构造时,为什么不删除 std::optional 的移动构造函数?

C++使用子类从模板继承

c++ - 如何使用模板类查询 if(T==int)

c# - 如何在 C# 中处理组合类