使用模板化继承调用祖父构造函数

Invoking Grandparent constructor with templated inheritance

本文关键字:调用 构造函数 继承      更新时间:2023-10-16

我选择使用模板化继承以避免多重和虚拟继承。我的目标是使各种子代(4 或 5 代或我无法控制的继承)具有一个通用函数调用,无论它们派生什么。

我的解决方案是插入模板继承,如下所示:

template <typename BASE>
class common_call : public BASE {
public:
    void foo() { /*implementation independent of base*/ }
};
class child1 : public common_call <base1> {};
class child2 : public common_call <base2> {};

这有调用 base 构造函数的问题。类 base1 和 base2(不是我写的)有不同的构造函数,我必须在初始化列表中调用这些构造函数。common_call模板对这些构造函数一无所知,但子类执行它们当前直接继承的方式。

我有什么办法可以做到这一点:

class child3 : public common_call<base3>{
public:
    child3(param1, param2) : base3(param2) {/*do things here*/}
};

如果可能的话,我试图避免为每种类型的基础进行部分模板专业化。

如果您使用如下所示的可变参数模板为common_call提供模板化构造函数:

template <typename BASE>
class common_call : public BASE 
{
public:
    // C++11 variadic templates to define whole range of constructors
    template<typename... Args>
    common_call(Args&&... args)
    :
        BASE(std::forward<Args>(args)...)
    {}
    void foo() { /*implementation independent of base*/ }
};

然后,您可以使用任何模板参数从common_call派生(例如 base3 ) 并调用该类定义的任何构造函数

class child3
:
    public common_call<base3>
{
public:
    child3(Type1 param1, Type2 param2)
    :
        common_call(param2), // call constructor overload with 1 parameter of Type2
        t1_(param1)          // initialize t1_ member
    {}
private:
    Type1 t1_;
};