C++ 模板的编译链接讨论

//头文件

#ifndef Test_h__

#define Test_h__

template<class T>

class Test1

{

public:

static T Add(const T& x, const T& y);

};

#endif // Test_h__

//cpp文件

#include "Test.h"

template<class T>

T Test1<T>::Add(const T& x, const T& y)

{

return x + y;

}

//使用地方

Test1<int>::Add(1, 2);

以上编译会出现,链接问题,原因是,类模板必须显示初始化,也就是告诉具体类型

解决办法:

//修改后的cpp文件

#include "Test.h"

template<class T>

T Test1<T>::Add(const T& x, const T& y)

{

return x + y;

}

//要声明一次

template

int Test1<int>::Add(const int& x, const int& y);

顺便编译通过!

相关推荐
ZouZou老师1 小时前
C++设计模式之工厂方法模式:以家具生产为例
c++·设计模式·工厂方法模式
fish_xk4 小时前
c++中的引用和数组
开发语言·c++
有点。7 小时前
C++ ⼀级 2024 年 03 ⽉
c++
CC.GG8 小时前
【C++】二叉搜索树
java·c++·redis
Savior`L9 小时前
二分算法及常见用法
数据结构·c++·算法
深海潜水员9 小时前
OpenGL 学习笔记 第一章:绘制一个窗口
c++·笔记·学习·图形渲染·opengl
mmz120710 小时前
前缀和问题(c++)
c++·算法·图论
ULTRA??10 小时前
初学protobuf,C++应用例子(AI辅助)
c++·python
旖旎夜光10 小时前
list实现(7)(上)
c++
不会c嘎嘎10 小时前
深入理解 C++ 异常机制:从原理到工程实践
开发语言·c++