编译错误-模板化继承类中的c++成员变量初始化
compiler errors - 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;
}
但是我从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-initializer, T::value
称为mem-initializer-id。根据[class.base.]init) p2,
除非 memalalizer -id指定构造函数的类、构造函数类的非静态数据成员或该类的直接基或虚基,否则 memalalizer 是病态的。
可以调用基类的构造函数,并让它初始化成员。在本例中,您只需要将T::value(std::move(arg.value))
更改为T(std::move(arg.value))
。演示。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗