繁体   English   中英

调用具有模板化继承的祖父母构造函数

[英]Invoking Grandparent constructor with templated inheritance

我选择使用模板化继承以避免多重继承和虚拟继承。 我的目标是使各种子代(我不控制的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*/ }
};

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

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_;
};

暂无
暂无

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

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