问题描述
在编写模板化类时,我喜欢将实现移动到不同的文件 (myclass.tpp
) 并将其包含在主标题的底部 (myclass.hpp
>).
When writing templated classes, I like to move the implementation into a different file (myclass.tpp
) and include it at the bottom of the main header (myclass.hpp
).
我的问题是:我需要在 .tpp
文件中包含守卫还是将它们包含在 .hpp
文件中就足够了?
My Question is: do I need include guards in the .tpp
file or is it sufficient to have them in the .hpp
file?
示例代码:
myclass.hpp
#ifndef MYCLASS_HPP
#define MYCLASS_HPP
template<typename T>
class MyClass
{
public:
T foo(T obj);
};
//include template implemetation
#include "myclass.tpp"
#endif
myclass.tpp
#ifndef MYCLASS_TPP //needed?
#define MYCLASS_TPP //needed?
template<typename T>
T MyClass<T>::foo(T obj)
{
return obj;
}
#endif //needed?
推荐答案
从不需要包含守卫:它们非常有用、便宜、无破坏性和预期.所以是的,您应该使用标题保护来保护这两个文件:
Include guards are never needed: they're just terribly useful, cheap, non-disruptive and expected. So Yes, you should protect both files with header guards:
- 非常有用:它们允许您声明多个文件的依赖项,而无需跟踪已包含哪些文件.
- 便宜:这只是一些预编译标记.
- 非破坏性:它们非常适合
#include
的大多数用例(我有一个不知道如何编写宏的同事,所以他#include
d 实现文件 facepalm). - 预期:开发人员知道它们是什么,但几乎没有注意到它们;相反,缺少包含保护的头文件会唤醒我们并添加到全局 wtf/line 计数器中.
- Terribly useful: they allow you to declare a dependency from multiple files without keeping track of which files have already been included.
- Cheap: this is just some precompilation tokens.
- Non-disruptive: they fit well with most use-cases of
#include
(I've had a colleague who didn't know how to write macros so he#include
d implementation files facepalm). - Expected: developers know what they are and barely notice them; on the contrary a header file missing include guards wakes us up and adds to the global wtf/line counter.
我借此机会强调 StoryTeller 的评论:
I take the opportunity to highlight the comment from StoryTeller:
如果未定义 hpp 防护,我会更进一步并添加一个描述性的 #error
指令.只是为了提供一点保护,包括首先对人的保护.
翻译成:
#ifndef MYCLASS_TPP
#define MYCLASS_TPP
#ifndef MYCLASS_HPP
#error __FILE__ should only be included from myclass.hpp.
#endif // MYCLASS_HPP
template<typename T>
T MyClass<T>::foo(T obj)
{
return obj;
}
#endif // MYCLASS_TPP
注意:如果翻译单元先#include
然后#include
,则不会触发任何错误,一切正常很好.
Notice: if a translation unit first #include <myclass.hpp>
and then #include <myclass.tpp>
, no error is fired and everything is fine.
这篇关于模板 (.tpp) 文件包含保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!