问题描述
通常,当我创建一个类,我创建一个头和该类的源。我听说有一个模板类,你必须把函数实现在标题。我试着做这两种方式,并得到编译错误第一种方式。第二种方式工作正常。但是,我喜欢将我的代码组织成头文件和源文件,所以是否可以把函数实现放入源文件?
Normally when I create a class, I create a header and a source for that class. I have heard that with a template class, you have to put the function implementation in the header. I tried doing it both ways, and got compilation errors the first way. The second way worked fine. However, I like to organize my code into headers and source files, so is it possible to put the function implementations into a source file? (Maybe it requires special compilation flags or syntax?) Or should I just keep em in the header?
谢谢!
推荐答案
通常,所有模板代码必须在头文件中,因为编译器需要在实例化时知道完整的类型。
Generally, all template code must be in a header file since the compiler needs to know the complete type at the point of instantiation.
正如Aaron所说,在具体情况下,可以将实现细节放在 .cpp
-file中,你知道所有可能的类型模板将被实例化并使用这些类型显式实例化它。
As Aaron says below it is possible to put the implementation details in a .cpp
-file in the specific case where you know on before hand all possible types the template will be instantiated with and explicitly instantiate it with those types. You'll then get a linker error if the template gets instantiated with another type somewhere in your code.
一个相当普通的解决方案,至少在视觉上将接口与实现分开是一个很常见的解决方案,将所有实现放在 .inc
(或 .tcc
或 .ipp $
A quite common general solution to at least visually separate interface from implementation is to put all implementation in a .inc
(or .tcc
or .ipp
)-file and include it at the end of the header file.
请注意,将模板类成员放在类定义之外的语法(无论你是否使用具体的解决方案或一般)略有繁琐。您需要在test.h中输入:
Note that the syntax for putting template class members outside the class-definition (whether you use the specific solution or the general) is slightly cumbersome. You'll need to write:
// in test.h
template <class A>
class Test
{
public:
void testFunction();
};
#include "test.inc"
// in test.inc
template <class A>
void Test<A>::testFunction()
{
// do something
}
这篇关于做模板类的成员函数实现总是要在C ++的头文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!