<分区>
Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?
例如,在定义模板类时,为什么类方法的实现需要在 header 中?为什么它们不能在实现文件 (cpp/cxx) 中?
<分区>
Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?
例如,在定义模板类时,为什么类方法的实现需要在 header 中?为什么它们不能在实现文件 (cpp/cxx) 中?
最佳答案
模板类不是类,它是可用于创建类的模板。当您实例化这样一个类时,例如MyTemplate<int>
,编译器当场创建类。为了创建它,它必须查看所有模板化成员函数(以便它可以使用模板创建实际成员函数,例如 MyTemplate<int>::foo()
),因此这些模板化成员函数必须在标题中。
如果成员不在 header 中,编译器将简单地假定它们存在于其他地方,并根据模板化函数声明创建实际的函数声明,这会给您带来链接器错误。
“export”关键字应该可以解决这个问题,但很少有编译器支持它(我只知道 Comeau)。
你也可以显式实例化MyTemplate<int>
- 然后编译器将为 MyTemplate<int>
创建实际的成员函数当它编译包含 MyTemplate
的 cpp 文件时成员函数定义模板。
关于c++ - 为什么 C++ 模板定义需要在标题中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5180357/