模板静态var =未定义的引用
template static var = undefined reference
此代码在MSVC中运行良好,但根据gcc-4.7.2 c++ 11,链接器会出现以下问题。怎么了
演示错误:/home/r7Qecv/ccEZjv1w.o: In function `main':
prog.cpp:(.text.startup+0xa): undefined reference to `Foo<long>::s'
prog.cpp:(.text.startup+0x17): undefined reference to `Foo<int>::s'
prog.cpp:(.text.startup+0x2c): undefined reference to `Foo<long>::s'
collect2: error: ld returned 1 exit status
代码#include <iostream>
#include <stack>
using namespace std;
template<class T>
class Foo{
public:
T a;
static T s;
};
template<>
int Foo<int>::s;
template<>
long Foo<long>::s;
int main(){
Foo<int> f;
Foo<long> f2;
f.a=4;
f.s=6;
f2.a=8;
std::cout<<f2.s;
f2.s=11;
return 0;
}
您还没有实例化静态成员,您只是声明了它们。
这样做(或类似):
template<>
int Foo<int>::s = 0;
template<>
long Foo<long>::s = 0;
答案是,您需要初始化静态成员以使其成为定义:
14.7.3p13
模板的静态数据成员的显式专门化是如果声明包含初始化式,则定义;否则,它是一个声明。
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用