c++模板和头文件 [英] c++ template and header files

查看:33
本文介绍了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++模板和头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆