编译错误-模板化继承类中的c++成员变量初始化

compiler errors - C++ Member variable initialization in templated inherited class

本文关键字:c++ 成员 初始化 变量 继承 错误 编译      更新时间:2023-10-16

我想弄清楚这段代码有什么问题。基本上,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;
}

但是我从clang中得到以下错误:

    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想把(可能也是clang) 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)) {}
                                                   ^

不能在构造函数初始化列表中初始化基类的成员。

在标准语言中,type2(T&& arg) : T::value(std::move(arg.value)) {}中的T::value(std::move(arg.value))称为mem-initializerT::value称为mem-initializer-id。根据[class.base.]init) p2,

除非 memalalizer -id指定构造函数的类、构造函数类的非静态数据成员或该类的直接基或虚基,否则 memalalizer 是病态的。

可以调用基类的构造函数,并让它初始化成员。在本例中,您只需要将T::value(std::move(arg.value))更改为T(std::move(arg.value))。演示。