簡體   English   中英

模板繼承類中的C ++成員變量初始化

[英]C++ Member variable initialization in templated inherited class

我試圖找出這段代碼有什么問題。 基本上, type2繼承自type1<T>, type1<T2> ,我想從一個基類中初始化value成員。

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

但是我從c得到以下錯誤:

    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.

為什么clang說typename specifier refers to non-type member 'value' in 'type1<int>' Gcc希望將value (可能也是clang)視為一種類型:

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)) {}
                                                   ^

您不能在構造函數初始值設定項列表中初始化基類的成員。

在Standardese, T::value(std::move(arg.value))type2(T&& arg) : T::value(std::move(arg.value)) {}稱為MEM-初始化 ,並T::value稱為mem-initializer-id 根據[class.base.init] p2

除非MEM-初始化ID名稱的構造函數的類,構造函數的類的非靜態數據成員,或者該類的直接或虛擬基地,形成不良的MEM-初始化

您可以調用基類的構造函數,並使其初始化成員。 在這種情況下,您只需要將T::value(std::move(arg.value))更改為T(std::move(arg.value)) 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM