[英]Error defining const static member of class if the class has template
I have the following code in a .h
file:我在
.h
文件中有以下代码:
class Test1 {
struct A1 {
int x;
};
static const A1 a1;
};
template <class T>
class Test2 {
struct A2 {
int x;
};
static const A2 a2;
};
and I define values for both a1
and a2
in a .cpp
file:我在
.cpp
文件中定义了a1
和a2
的值:
const Test1::A1 Test1::a1 = { 5 };
template<class T>
const Test2<T>::A2 Test2<T>::a2 = { 5 };
The odd thing is that for Test1
everything works, but for Test2
I get the following error in the last line of the .cpp
file:奇怪的是,对于
Test1
,一切正常,但对于Test2
,我在.cpp
文件的最后一行出现以下错误:
Error C2061 syntax error: identifier 'A2'
The only difference between Test1
and Test2
is that Test2
has a template. Test1
和Test2
之间的唯一区别是Test2
有一个模板。 Why is this a problem, and how can I fix it?为什么这是一个问题,我该如何解决? Also, this works as well:
此外,这也适用:
test.h
struct A3 {
int x;
};
template <class T>
class Test3 {
static const A3 a3;
};
test.cpp
template<class T>
const A3 Test3<T>::a3 = { 5 };
So the problem is with using a struct defined in a templated class, but I can't find out what exactly is the problem.所以问题在于使用模板化 class 中定义的结构,但我无法找出问题所在。
(I'm compiling with c++14.) (我正在使用 c++14 进行编译。)
The fix is suggested by a compiler, just be more careful in reading the compiler messages.该修复程序由编译器建议,只是在阅读编译器消息时更加小心。
<source>(17): warning C4346: 'A2': dependent name is not a type
<source>(17): note: prefix with 'typename' to indicate a type
<source>(17): error C2061: syntax error: identifier 'A2'
<source>(17): error C2143: syntax error: missing ';' before '{'
<source>(17): error C2447: '{': missing function header (old-style formal list?)
Or或者
<source>:17:7: error: missing 'typename' prior to dependent type name 'Test2<T>::A2'
const Test2<T>::A2 Test2<T>::a2 = { 5 };
^~~~~~~~~~~~
typename
1 error generated.
That means the correct code:这意味着正确的代码:
template<class T>
const typename Test2<T>::A2 Test2<T>::a2 = { 5 };
Read more: Why do we need typename here?阅读更多: 为什么我们需要 typename 在这里? .
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.