使用模板化继承调用祖父构造函数
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*/ }
};
然后,您可以使用任何模板参数从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_;
};
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素