Mah*_*esh 1 c++ gcc templates visual-studio-2010 visual-c++
摘自大卫,尼古拉的书 - C++模板:完整指南
因此,模板编译两次:
- 在没有实例化的情况下,检查模板代码本身的语法是否正确.发现语法错误,例如缺少分号.
- 在实例化时,检查模板代码以确保所有调用都有效.发现无效调用,例如不支持的函数调用.
保持第一点,我写道 -
template<typename T>
void foo( T x)
{
some illegal text
}
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它在Visual Studio 2010上构建正常,没有关闭优化的任何警告.但是,它在gcc-4.3.4上失败了.哪一个符合C++标准?即使没有模板实例化,模板代码也必须编译吗?
有问题的程序格式不正确,但C++标准在这种情况下不需要诊断,因此Visual Studio和GCC都以兼容的方式运行.从C++ 03标准的§14.6/ 7(强调我的):
知道哪些名称是类型名称允许检查每个模板定义的语法.不能为可以生成有效特化的模板定义发出诊断.如果无法为模板定义生成有效的专业化,并且未实例化该模板,则模板定义格式错误,无需诊断.如果非依赖名称中使用的类型在定义模板但在完成实例化时完成,并且该类型的完整性影响程序是否良好时,则不完整形成或影响程序的语义,该程序是不正确的; 无需诊断.[ 注意:如果实例化模板,将根据本标准中的其他规则诊断错误.确切地说,这些错误被诊断出来是一个实施质量问题.] [ 例子:
Run Code Online (Sandbox Code Playgroud)int j; template<class T> class X { // ... void f(T t, int i, char* p) { t = i; // diagnosed if X::f is instantiated // and the assignment to t is an error p = i; // may be diagnosed even if X::f is // not instantiated p = j; // may be diagnosed even if X::f is // not instantiated } void g(T t) { +; //may be diagnosed even if X::g is // not instantiated } };- 结束例子 ]