c++ template and header files(c++模板和头文件)
问题描述
所以,我听说 C++ 模板不应该分为头文件 (.h) 和源文件 (.cpp).
So, I heard that C++ templates shouldn't be separated into a header (.h) and source (.cpp) files.
例如,这样的模板:
template <class T>
class J
{
T something;
};
这是真的吗?为什么会这样?
Is this true? Why is it so?
如果因此我必须将声明和实现放在同一个文件中,我应该将它放在 .h 文件还是 .cpp 文件中?
If because of that I'm gonna have to put both declaration and implementation in the same file, should I put it in a .h file or a .cpp file?
推荐答案
Headers.
这是因为模板是在编译时而不是链接时实例化的,并且不同的翻译单元(大致相当于您的 .cpp
文件)仅在链接时相互了解".标头往往在编译时被广泛了解",因为您在任何需要它们的翻译单元中#include
它们.
It's because templates are instantiated at compile-time, not link-time, and different translation units (roughly equivalent to your .cpp
files) only "know about" each other at link-time. Headers tend to be widely "known about" at compile-time because you #include
them in any translation unit that needs them.
阅读 https://isocpp.org/wiki/faq/templates 了解更多信息.
Read https://isocpp.org/wiki/faq/templates for more.
这篇关于c++模板和头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++模板和头文件


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01