c++ - 可变参数模板的多重继承 : how to call function for each base class?

标签 c++ c++11 variadic-templates

我有一个菱形继承(钻石问题)方案,最后一个 child 应该能够从许多不同的 parent 那里继承。

     A
    /|\
   / | \
  B  C  ...
  |  |  |
    * *
    D E

现在假设我有一个 class D : public B, class E : public B, public C 等。从 D 我想要调用其所有 parent 的相同功能,我保证由于继承而存在。我的想法是我可以将它包装在一些可变参数模板中。

目前我有这个:

template <typename T>
class A
{
public:
    A(T t) : mT(t) {}
    virtual ~A() {}
    virtual void doThings() = 0;
protected:
    T mT;
};

template <typename T, typename A = A<T>>
class B : public A
{
public:
    B(T t) : A(t) {}
    virtual ~B() {}
    virtual void doThings() { std::cout << "B" << std::endl; }
};

template <typename T, typename A = A<T>>
class C : public A
{
public:
    C(T t) : A(t) {}
    virtual ~C() {}
    virtual void doThings() { std::cout << "C" << std::endl; }
};

现在我想我可以做这样的事情,这显然行不通:

template <typename T, typename ...Args>
class ChildGenerator : public Args...
{
public:
    ChildGenerator(T t) : Args(t)... {}

    // The unpacking of the variadic template does not work here.
    // Do I need to make it recursive somehow? How can I do that without having to instantiate new classes B and C?
    void doThings() override { Args...::doThings();}
};

我希望我可以像这样使用它:

int main()
{
    using B = B<double>;
    using C = C<double>;
    B c1(0.0);
    C c2(1.0);
    ChildGenerator<double, B, C> c3(2.0);
    c1.doThings();
    c2.doThings();
    c3.doThings();
 }

预期输出(顺序无关紧要):

B
C
B // <-- order of these two does not matter
C // <--

我想要实现的目标是否可行?

最佳答案

迭代可 rebase 数的一种方法:

template <typename T, typename ...Args>
class ChildGenerator : public Args...
{
public:
    ChildGenerator(T t) : Args(t)... {}

    void doThings() override {
        int dummy[] = {0, (Args::doThings(), void(), 0)...};
        static_cast<void>(dummy); // avoid warning for unused variable
    }
};

或者在 C++17 中,使用折叠表达式:

    void doThings() override {
        (static_cast<void>(Args::doThings()), ...);
    }

关于c++ - 可变参数模板的多重继承 : how to call function for each base class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322854/

相关文章:

c++ - 继承前向声明的结构?

C++ LoadLibrary ERROR_NOACCESS "Invalid access to memory location."

c++: 'std::is_fundamental' 的替代方案?

c++ - 用 clang 和 libc++ 编译 cln

c++ - 在 C++11 中将(1 元组到 10 元组)参数转换为 n 元组参数

c++ - 将 C++ 项目升级到 VS2010,现在出现 AccessViolationException

c++ - 在 C++ 宏 "int val = rand()"中创建新值

c++ - 在 gdb 中使用 [] 运算符和 unordered_map 给出未解析的运算符

c++ - 可变结构规范

c++ - 按类型获取具有递归继承的可变参数模板的阴影成员