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++模板和头文件


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01