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/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07