【问题标题】:Call matching methods from inherited classes从继承的类调用匹配方法
【发布时间】:2016-06-20 09:03:01
【问题描述】:

从一个继承了具有相同方法名称的其他 3 个基类的单个类调用匹配方法的最佳方法是什么?我想从一个调用中调用这些方法,不知道它是否可能

template<typename T>
class fooBase()
{
    void on1msTimer();
    /* other methods that make usage of the template */
}

class foo
    : public fooBase<uint8_t>
    , public fooBase<uint16_t>
    , public fooBase<float>
{
    void onTimer()
    {
         // here i want to call the on1msTimer() method from each base class inherited 
         // but preferably without explicitly calling on1msTimer method for each base class
    }
}

有没有办法做到这一点? 谢谢

【问题讨论】:

  • 如果你想调用三个不同的函数,你必须告诉编译器你想调用哪三个函数。
  • 一种选择是让所有基类虚拟地从事件调度器继承,并在构造期间向调度器注册它们自己的实现。然后派生最多的类可以通过调度程序调用函数列表。

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


【解决方案1】:

一次调用不可能同时获取所有三个成员函数。想象一下,这些成员函数会返回 void 以外的其他内容:您期望哪个返回值?!

如果你想调用所有三个基类的on1msTimer(),你需要显式调用它们:

void onTimer()
{
     fooBase<float>::on1msTimer();
     fooBase<uint8_t>::on1msTimer();
     fooBase<uint16_t>::on1msTimer();
}

Online demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多