当前位置:网站首页>模板类的声明和定义
模板类的声明和定义
2022-07-17 04:59:00 【maplezys】
模板类的实现可以放到.cpp文件里吗?
先放结论:涉及到模板和模板特例化时,一般最好将模板和模板特例化一起放在对应的.h文件中。
以下面的代码为例:
//---test.h---//
template<typename T>
class A {
public:
void f(); //这里只是声明
};
//---test.cpp---//
#include "test.h"
template<typename T>
void A<T>::f() {
// do somethong...
}
//---main.cpp---//
#include "test.h"
int main(){
A<int> a;
a.f();
}
在main函数中,编译器并不知道A::f的定义,因为它不再test.h文件里面,于是编译器只好寄希望于连接器,希望它能够在其他的.obj里面找到A::f的实现体,在上述的例子中就是test.obj。然而,test.obj中是没有A::f的二进制代码的。因为C++明确表示当一个模板不被用到的时候它就不该被具现出来,而此处的test.cpp是没有用到A::f的,于是在test.obj中是没有关于它的二进制代码的,于是连接器便会给出连接错误。但是,如果在test.cpp中写一个函数,其中使用到了A::f,则编译器便会将其具现出来,即使main函数中没有用到。
解决方法:
- 在实例化要素中让编译器看到模板定义
- 用另外的文件来显式地实例化类型,这样连接器就能看到该类型
- 使用export关键字(大部分编译不支持)
第一种方法就是将模板的声明和定义全卸载.h文件中,这样编译器就能直接编译main.cpp。第二种便是新建一个文件,或者就在test.cpp中,显式地实例化得到类型,这样便会被连接器找到相对饮管道二进制代码。
边栏推荐
- [TA frost wolf _may - "hundred people plan"] art 2.1 DCC tool chain and engine tool chain
- Time frequency diagram classification challenge of intelligent hardware voice control 2.0 (ideas and results, currently top5)
- Tidb learning
- Autojs learning - map finding data generation
- AutoJs学习-实现极乐净土
- TiDB 性能分析和优化
- masm32写程序
- N-Beats模型于2020年发布,并且优于M4比赛的获胜者3%!
- 数据库与开源的未来
- Redis cluster interview questions
猜你喜欢

Extreme video compression using the pellet toolbox

Wechat applet source code of high imitation Netease cloud music UI

2022最新版校园跑腿小程序源码

【FPGA教程案例27】通过Verilog实现双口RAM乒乓结构

Eureka,拿捏日千万级访问量妥妥的!

Tasking 新建 AURIX TC37X demo 工程

Easyexcel easy to use

Emqx pressure test tread pit for your reference

Water and electricity meter reading and recharge management system in Colleges and universities in property community

MySQL表的查询进阶
随机推荐
探索:制药厂系统网络时钟同步(NTP时间同步服务器)
[Lipschitz] simulation of Lipschitz Lipschitz exponent based on MATLAB
VirtualLab基础实验教程-7.偏振(3)
mysql8.026-- 视图(下)
Constraints on MySQL tables (Basics)
Autojs learning - map finding data generation
力扣刷题02(三数之和+最大子序和+二叉树最近公共祖先)
物业小区高校水电抄表充值管理系统
Virtual lab basic experiment tutorial -7 Polarization (3)
【TA-霜狼_may-《百人计划》】基础渲染光照介绍(一)
MySQL InnoDB transaction related records
Eureka,拿捏日千万级访问量妥妥的!
MySQL one line to many lines (split according to specific symbols)
MySQL表的约束(基础篇)
手机平台上的用户空间锁概述
Golang reverse slice code example
Fudan micro fmql (domestic zynq) [PS of IAR bare metal development] - non byte aligned access
常用postgresql数据操作备忘(不定时更新)
UE-插件 ElectronicNodes 5.0.0/4.23-4.27
【TA-霜狼_may-《百人计划》】美术2.1 DCC工具链与引擎工具链