Bil*_*ias 7 c++ templates include-guards
在模板类中包含保护是明智的吗?
每次使用不同的实现引用它们时,是不是应该重新分析模板类?
NB在Visual C++ 2008中,我没有将两者结合起来的错误......
小智 12
你需要包括警卫.考虑以下代码:
// this is t.h
template <typename T>
void f( T t ) {
}
// this is t.cpp
#include "t.h"
#include "t.h"
int main() {
f( 1 );
}
Run Code Online (Sandbox Code Playgroud)
这给出了错误:
t.h:2: error: redefinition of 'template<class T> void f(T)'
t.h:2: error: 'template<class T> void f(T)' previously declared here
Run Code Online (Sandbox Code Playgroud)
此外,包含模板的标头通常还包含非模板代码.
模板定义应该被解析一次(这里有两个阶段的名称查找,这样就可以在没有实例化的情况下立即给出尽可能多的错误).实例化使用当时构建的内部数据结构完成.
模板定义通常(即如果你没有使用export或做一些特殊的事情)在头文件中应该有它们的包含保护.添加一个模板定义是没用的,但没有害处.