模板静态var =未定义的引用

template static var = undefined reference

本文关键字:未定义 引用 var 静态      更新时间:2023-10-16

此代码在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

模板的静态数据成员的显式专门化是如果声明包含初始化式,则定义;否则,它是一个声明。