繁体   English   中英

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

[英]Derived class not calling member function of base class

假设我有一个类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 ,并在event_callable::m_funcs搜索operator() 您应该使用虚拟继承来克服此问题:

class event_callable: public virtual event_base { ... };
class event_mutable: public virtual event_base { ... };

class event: public event_callable, public event_mutable { ... };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM