当前位置:网站首页>可否把模板的头文件和源文件分开编译
可否把模板的头文件和源文件分开编译
2022-04-23 14:01:00 【JokerYourMemory】
严格意义上说,不行,不过可以通过巧妙的手段解决这问题。
先说为啥不行:引用这篇文章的例子 为什么C++编译器不能支持对模板的分离式编译,
//-------------test.h----------------//
template<class T>
class A
{
public:
void f(); // 这里只是个声明
};
//---------------test.cpp-------------//
#include”test.h”
template<class T>
void A<T>::f() // 模板的实现
{
…//do something
}
//---------------main.cpp---------------//
#include”test.h”
int main()
{
A<int> a;
f(); // #1
}
说白了 就是函数模板也好、类模板也罢,在编译的时候实例化为函数定义(能不能实例化要看编译器是否能遇让模板实例出来 的语句)。而跨文件函数调用是在链接的时候才去找实例化之后 的函数。由于头文件仅作为声明模板类或者函数的地方。相应的CPP仅仅作为实现的地方的话,那么是不会触发其实例化的,也就是这个CPP对应的.OBJ文件中没有具体的函数信息。这就是个麻烦了。
那如何解决呢?
两种思路,暂时没想到其它的
第一种是让模板知道main函数是如何调用他的,那么需要把模板的定义放到头文件中去,然后main函数的cpp包含这个头文件中即可。但是如果多个类、都用了这个方法,那么在编译的时候会产生重复定义的问题,类似我上一篇文章全局变量能不能放到头文件中声明。
另外一种思路是,让.h共享.cpp的信息,即在.h中增加#include<.cpp>,但是这种.h包含.cpp的做法是否严谨呢。
还有一种办法,就是既然无法链接是因为编译的时候没有经过调用生成类实例,那么能否通过独立的函数来调用这个类或者函数 来生成一个呢。也可以,但是依然面对着第一种做法的重复定义的风险。
版权声明
本文为[JokerYourMemory]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_38084180/article/details/80501311
边栏推荐
- Oracle alarm log alert Chinese trace and trace files
- 多线程 @Async 线程池
- Express middleware ③ (custom Middleware)
- nodejs通过require读取本地json文件出现Unexpected token / in JSON at position
- China creates vast research infrastructure to support ambitious climate goals
- L2-024 tribe (25 points)
- Introduction to spark basic operation
- Android 面试主题集合整理
- go 语言 数组,字符串,切片
- 解决方案架构师的小锦囊 - 架构图的 5 种类型
猜你喜欢
The art of automation
groutine
elmo(BiLSTM-CRF+elmo)(Conll-2003 命名实体识别NER)
【报名】TF54:工程师成长地图与卓越研发组织打造
Android 面试主题集合整理
专题测试05·二重积分【李艳芳全程班】
scikit-learn构建模型的万能模板
Crontab timing task output generates a large number of mail and runs out of file system inode problem processing
SQL数据库
Interesting talk about network protocol
随机推荐
SQL: How to parse Microsoft Transact-SQL Statements in C# and to match the column aliases of a view
Nodejs安装及环境配置
Question bank and answer analysis of the 2022 simulated examination of the latest eight members of Jiangxi construction (quality control)
STM32学习记录0007——新建工程(基于寄存器版)
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
Android interview theme collection
Choreographer full resolution
分页SQL
Oracle告警日志alert.log和跟踪trace文件中文乱码显示
1256: bouquet for algenon
Android篇:2019初中级Android开发社招面试解答(中
YARN线上动态资源调优
Redis docker 安装
The latest development of fed digital currency
分库分表 & ShardingSphere
Haruki Murakami -- Excerpt from "what do I talk about when I talk about running"
Introduction to spark basic operation
生产环境——
linux安装mysql后修改密码
go 语言 数组,字符串,切片