Why do C++ template definitions need to be in the header?(为什么 C++ 模板定义需要在头文件中?)
问题描述
可能的重复:
为什么应该模板类的实现和声明在同一个头文件中?
例如在定义模板类时,为什么类方法的实现需要在标题中?为什么它们不能在实现文件 (cpp/cxx) 中?
e.g when defining a template class why do the implementations of the class methods need to be in the header? Why can't they be in a implementation file (cpp/cxx)?
推荐答案
模板类不是类,而是可用于创建类的模板.当你实例化这样一个类时,例如MyTemplate
,编译器当场创建类.为了创建它,它必须查看所有模板化的成员函数(以便它可以使用模板创建实际的成员函数,例如 MyTemplate
),因此这些模板化的成员函数必须在头文件中.
A template class is not a class, it's a template that can be used to create a class. When you instantiate such a class, e.g. MyTemplate<int>
, the compiler creates the class on the spot. In order to create it, it has to see all the templated member functions (so that it can use the templates to create actual member functions such as MyTemplate<int>::foo()
), and therefore these templated member functions must be in the header.
如果成员不在头文件中,编译器将简单地假设它们存在于其他地方,并从模板化的函数声明中创建实际的函数声明,这会导致链接器错误.
If the members are not in the header, the compiler will simply assume that they exist somewhere else and just create actual function declarations from the templated function declarations, and this gives you linker errors.
"export" 关键字应该可以解决这个问题,但很少有编译器支持它(我只知道 Comeau).
The "export" keyword is supposed to fix this, but few compilers support it (I only know of Comeau).
您也可以显式实例化 MyTemplate
- 然后编译器会在编译包含 MyTemplate
成员函数定义模板.
You can also explicitly instantiate MyTemplate<int>
- then the compiler will create actual member functions for MyTemplate<int>
when it compiles the cpp files containing the MyTemplate
member function definition templates.
这篇关于为什么 C++ 模板定义需要在头文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++ 模板定义需要在头文件中?


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