Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

https://blog.csdn.net/zhizhengguan/article/details/116108271

语法1:定义在.h

.h文件:

template <typename T>
class the_class{
    static int id;
};

template <typename T>
int the_class<T>::id = 0;

编译链接为模板类static成员分配的地址

这个取决于链接器,有些版本的链接器不支持此特殊处理,会报错,那么用语法2

由于定义在头文件中,如果多个.cpp文件包含了此头文件会导致有多个定义的问题,
情况比如:
call1.cpp

#include <iostream>
#include "the_class.h"

void call1(){
    the_class<int> c;
    std::cout << c.id << "\n";
};

call2.cpp

#include <iostream>
#include "the_class.h"

void call2(){
    the_class<int> c;
    std::cout << c.id << "\n";
};

main.cpp

#include <string>
#include <iostream>

void call1();
void call2();

int main(){
    call1();
    call2();
    return 0;
}

call1.cpp和call2.cpp定义的call1()和call2()两个函数都生成了类模板the_class的实例the_class编译器会分别在编译两个代码文件所生成的目标文件中,为其静态成员变量the_class<int>::id分配内存地址。而按照类静态成员的概念,所有类实例应该共享同一套静态成员存储空间。在链接时链接器将随机选择一个目标中的空间作为最终存储空间,从而使不同目标文件中的多个等价目标实例共享同一套静态成员空间。

语法2:定义在.cpp

和模板类成员函数定义和申明分离的写法类似,要在.cpp文件中写对模板类的实例化申明
.h文件:

template <typename T>
class the_class{
    static int id;
};

.cpp文件:

#include "the_class.h" 
 
template class the_class<int>;
template class the_class<long long>;

template <typename T>
int the_class<T>::id = 0;

评论