当前位置:网站首页>可否把模板的头文件和源文件分开编译
可否把模板的头文件和源文件分开编译
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
边栏推荐
- 大专的我,闭关苦学 56 天,含泪拿下阿里 offer,五轮面试,六个小时灵魂拷问
- Nodejs安装及环境配置
- Using Jupiter notebook in virtual environment
- JS brain burning interview question reward
- cnpm的诡异bug
- Express ② (routage)
- Kettle--控件解析
- Taobao released the baby prompt "your consumer protection deposit is insufficient, and the expiration protection has been started"
- Program compilation and debugging learning record
- What is the difference between blue-green publishing, rolling publishing and gray publishing?
猜你喜欢
随机推荐
项目中遇到的问题(五)操作Excel接口Poi的理解
JS force deduction brush question 103 Zigzag sequence traversal of binary tree
Tensorflow & pytorch common error reporting
About note 1
Choreographer全解析
基础知识学习记录
try --finally
[code analysis (1)] communication efficient learning of deep networks from decentralized data
PySide2
Express ② (routage)
Oracle告警日志alert.log和跟踪trace文件中文乱码显示
Redis docker 安装
专题测试05·二重积分【李艳芳全程班】
Kettle--控件解析
linux MySQL数据定时dump
What is the difference between blue-green publishing, rolling publishing and gray publishing?
3300万IOPS、39微秒延迟、碳足迹认证,谁在认真搞事情?
Function executes only the once function for the first time
Program compilation and debugging learning record
变长参数__VA_ARGS__ 和 写日志的宏定义








