模板类的静态const成员应按如下方式初始化:
template <typename T>
class TypeA{
public:
static const int INSTANCE = 1;
};
如果我们想要一个类TypeA的实例而不是一个int,那么正确的语法是什么?
例如:
#include <iostream>
template <typename T>
class TypeA{
public:
T mData;
TypeA(T data) : mData(data){}
static const TypeA<T> INSTANCE = TypeA<T>(1);
};
int main(int argc, char **argv){
std::cout << TypeA<int>::INSTANCE.mData << std::endl;
}
这会产生错误(gcc):
main.cpp||In instantiation of 'class TypeA<int>':|
main.cpp|14|required from here|
main.cpp|9|error: in-class initialization of static data member 'const TypeA<int> TypeA<int>::INSTANCE' of incomplete type|
main.cpp||In instantiation of 'const TypeA<int> TypeA<int>::INSTANCE':|
main.cpp|14|required from here|
main.cpp|9|error: in-class initialization of static data member 'const TypeA<int> TypeA<int>::INSTANCE' of non-literal type|
main.cpp|9|error: non-constant in-class initialization invalid for static member 'TypeA<int>::INSTANCE'|
main.cpp|9|error: (an out of class initialization is required)|
main.cpp|9|error: 'TypeA<int>::INSTANCE' cannot be initialized by a non-constant expression when being declared|
||=== Build finished: 5 errors, 4 warnings (0 minutes, 0 seconds) ===|
答案 0 :(得分:2)
只需按照编译器提供的说明进行操作:
main.cpp | 9 | error:静态数据成员'const TypeA TypeA :: INSTANCE'的类型初始化不完整类型|
您无法初始化尚未完全声明的类型。因此,您必须将初始化移出类声明:
#include <iostream>
template <typename T>
class TypeA{
public:
T mData;
TypeA(T data) : mData(data){}
static const TypeA<T> INSTANCE;
};
template <typename T>
const TypeA<T> TypeA<T>::INSTANCE = TypeA<T>(1);
int main(int argc, char **argv){
std::cout << TypeA<int>::INSTANCE.mData << std::endl;
}
答案 1 :(得分:0)
您无法在课程中初始化INSTANCE。你需要稍后再做。
#include <iostream>
template <typename T>
class TypeA{
public:
T mData;
TypeA(T data) : mData(data){}
static const TypeA<T> INSTANCE;
};
template <typename T> const TypeA<T> TypeA<T>::INSTANCE=TypeA<T>(1);
int main(int argc, char **argv){
std::cout << TypeA<int>::INSTANCE.mData << std::endl;
}