模板类并包含 C++ 中的守卫
在模板类周围包含防护措施是否明智?
每次使用不同的实现引用模板类时,难道不应该重新解析模板类吗?
注意:在 Visual C++ 2008 中,将两者结合起来没有出现任何错误...
Is it wise to have include guards around template classes?
Aren't template classes supposed to be reparsed each time you reference them with a different implementation?
N.B In Visual C++ 2008 I get no errors combining the two...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你需要包括警卫。考虑以下代码:
这会产生错误:
此外,包含模板的标头通常也包含非模板代码。
You need include guards. Consider this code:
This gives the error:
Also, the headers that contain templates routinely also contain non-template code.
模板定义应该解析一次(这里有两个阶段名称查找之类的东西,以便可以立即给出尽可能多的错误,而无需实例化)。实例化是使用当时构建的内部数据结构完成的。
模板定义通常(即,如果您不使用导出或执行某些特殊操作)位于应具有包含保护的头文件中。为模板定义添加一个虽然无用但无害。
Templates definitions are supposed to be parsed once (and things like two phases name lookup are here so that as much errors as possible can be given immediately without having an instantiation). Instantiations are done using the internal data structure built at that time.
Templates definitions are usually (i.e. if you aren't using
export
or doing something special) in header files which should have their include guard. Adding one for template definition is useless but not harmful.简短的回答:您计划多次包含任何定义的每个单元都应该有一个标头防护。这是有或没有模板的情况。
Short answer: Every unit you plan to include more than once with any definitions should have a header guard. That is with or without templates.
回答你的第一个问题:是的,在模板类周围包含防护是明智的,也是强制性的。或者更严格地围绕每个头文件的全部内容。
当头文件中有东西时,这是遵守单一定义规则的方法,这样它就可以共享并且仍然安全。可能还有其他头文件包含您的头文件。当编译器编译模块文件时,它可能会多次看到头文件的
#include
,但防护会在第二次及后续时间启动,以确保编译器只看到一次内容。编译器重新解析任何东西并不重要;这就是它的工作。您只需提供一次内容,编译器就会看到它,并可以根据需要多次引用它。
To answer your first question: Yes, it is wise, and mandatory, to have include guards around template classes. Or more strictly surrounding the entire contents of every header file.
This is the way to obey the One Definition Rule when you have stuff in header files, so that its shared around and still safe. There may be other header files that include yours. When the compiler compiles a module file, it may see a
#include
of your header file many times, but the guards kick-in on the second and subsequent times to make sure the compiler only sees the contents once.Its doesn't matter that the compiler reparses anything; that's its job. You just have to supply the contents once and then the compiler has seen it and can refer to it again as many times as it needs.