[英]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.