简体   繁体   English

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

[英]Invoking Grandparent constructor with templated inheritance

I've chosen to use templated inheritance in order to avoid muliple and virtual inheritance. 我选择使用模板化继承以避免多重继承和虚拟继承。 My goal is to make various children (4 or 5 generations or inheritance that I don't control) have a common function call regardless of what they derive. 我的目标是使各种子代(我不控制的4或5代或继承)具有通用的函数调用,无论它们衍生什么。

My solution is inserting a template inheritance as so: 我的解决方案是这样插入模板继承:

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

This has the problem of invoking the constructor of base. 这有调用base的构造函数的问题。 Classes base1 and base2 (not written by me) have different constructors that I must invoke in the initialization list. base1和base2类(不是我写的)具有必须在初始化列表中调用的不同构造函数。 The common_call template knows nothing about these constructors, but the child classes do as they currently inherit directly. common_call模板对这些构造函数一无所知,但是子类却像它们当前直接继承一样。

Is there any way for me to do this: 我有什么办法可以做到这一点:

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

I'm trying to avoid making partial template specializations for each type of base if possible. 如果可能的话,我试图避免对每种基础类型进行部分模板专门化。

If you give common_call a templated constructor using variadic templates like this: 如果使用如下可变参数模板为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*/ }
};

you can then derive from common_call with any template argument (eg base3 ) and call whatever constructor that class has defined 然后,您可以使用任何模板参数(例如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