C++模板实例化 - 与 STL 不同,为什么我的模板实例化必须始终是显式的?
我的任何一个 C++ 项目都会生成链接器错误,除非我为我创作和使用的每个模板化类/方法/函数包含显式模板实例化。
STL类似乎没有这样的问题。
是否有一些我可以遵守的简单行为准则(双关语),它允许像 STL 那样的延迟实例化?
感谢您的聆听。
Any one of my C++ projects will generate a linker error unless I include an explicit template instantiation for every templated class/method/function I author and use.
STL classes seem to have no such problem.
Is there some simple code of conduct (pun intended) I can adhere to which allows deferred instantiation like that of STL?
Thanks for listening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于模板,您需要将所有模板代码和方法放入标头而不是源文件中。标准库就是这样做的。
For templates you need to put all the template code and methods into headers rather than source files. The standard library does this.
您应该将模板的大部分部分放在头文件中。这同样适用于模板类以及普通类中的模板函数。
您应该了解此规则的例外情况是,当您专门化模板时,您需要将专门化放在implementation/.cpp 文件中,因为专门化是具体类型。另一方面,实际的模板定义需要运行多次,针对与模板一起使用的每个模板参数类型运行一次 - 因此它们必须放入头文件中(它们不是具体类型的)。
例如,将:
放在头文件中,并将其专门化为 int:
在 cpp 文件中,因为 int 版本是具体的、完全定义的函数,而 T 版本是模板定义,将多次使用以生成许多具体函数。
You should put most parts of a template within the header file. This applies equally to template classes as well as template functions within normal classes.
The exception that you should know to this rule is that when you specialize a template, you need to put the specialization in the implementation/.cpp file because a specialization is a concrete type. The actual template definitions on the other hand will need to be run through multiple times, one for each template parameter type used with the template - so they must go in the header file (they're not concrete type-wise).
e.g. put:
in the header file and its specialization for an int:
in the cpp file because the int version is a concrete, fully defined function whereas the T version is a template definition which will be used many time to generate many concrete functions.
大多数情况下,模板类完全在头文件中定义。如果编译器尚未遇到您正在使用的函数和模板参数的组合,这允许编译器动态生成代码体。
您仍然可以使用具有单独头文件和实现文件的模板,但它不太方便。正如您所发现的,您必须预测每个模板参数并将该组合放入实现文件中,以便编译器可以生成必要的代码。
Most of the time a template class is defined completely in the header file. This allows the compiler to generate the body of code on the fly if it hasn't already come across the combination of function and template parameters that you're using.
You can still use a template with separate header and implementation files, but it's much less convenient. As you've discovered, you must anticipate each template parameter and put that combination in the implementation file, so that the compiler can generate the necessary code.