0

私はこのコードで何が間違っているのか把握しようとしています。基本的にtype2type1<T>, type1<T2>から継承しており、valueのメンバーを基本クラスの1つから初期化したいと考えています。C++テンプレート化された継承クラスのメンバー変数の初期化

#include <utility> 

template <typename T> 
struct type1 { 
    using base_type = T; 

    template <typename... Args> type1(Args&&... args) : value(std::forward<Args>(args)...) {} 

    T value; 
}; 

template <typename... Ts> 
struct type2 : public Ts... { 
    template <typename T> 
    type2(T&& arg) : T::value(std::move(arg.value)) {} 
}; 

int main() 
{ 
    type2<type1<int>, type1<double>> x(type1<int>(10)); 
    return 0; 
} 

しかし、私は打ち鳴らすから次のエラーを取得する:

Error(s): 

source_file.cpp:15:25: error: typename specifier refers to non-type member 'value' in 'type1<int>' 
    type2(T&& arg) : T::value(std::move(arg.value)) {} 
         ^~~~~ 
source_file.cpp:20:38: note: in instantiation of function template specialization 'type2<type1<int>, type1<double> >::type2<type1<int> >' requested here 
    type2<type1<int>, type1<double>> x(type1<int>(10)); 
            ^
source_file.cpp:9:7: note: referenced member 'value' is declared here 
    T value; 
    ^
1 error generated. 

はなぜtypename specifier refers to non-type member 'value' in 'type1<int>'を言って打ち鳴らすのか? GCCは型として扱う(おそらくあまりにも打ち鳴らす)valueしたい:

Error(s): 

source_file.cpp: In instantiation of ‘type2<Ts>::type2(T&&) [with T = type1<int>; Ts = {type1<int>, type1<double>}]’: 
source_file.cpp:20:54: required from here 
source_file.cpp:15:51: error: no type named ‘value’ in ‘struct type1<int>’ 
    type2(T&& arg) : T::value(std::move(arg.value)) {} 
               ^

答えて

1

あなたは、コンストラクタの初期化子リストで基底クラスのメンバを初期化することはできません。 type2(T&& arg) : T::value(std::move(arg.value)) {}でStandardese、T::value(std::move(arg.value))

MEM-初期と呼ばれ、そしてT::valueMEM-初期-ID呼ばれます。 [class.base.init]p2

によるとMEM-初期化子-ID名コンストラクタのクラス、コンストラクタのクラスの非静的データメンバー、またはそのクラスの直接または仮想ベース、MEM-初期化子がない限りが不正です。

あなたは、基本クラスのコンストラクタを呼び出し、それがメンバーを初期化させることができます。この場合、T::value(std::move(arg.value))から​​に変更するだけです。 Demo

関連する問題