模板编译:gcc vs VS2010 [英] Templates compilation: gcc vs VS2010

查看:246
本文介绍了模板编译:gcc vs VS2010的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这本书 - David,Nicolai的C ++模板:完整指南

From the book - C++ Templates: The Complete Guide by David, Nicolai




Thus, templates are compiled twice:


  1. 如果没有实例化,则会检查模板代码本身是否有正确的语法。发现语法错误,例如缺少
    分号。

  2. 在实例化时,将检查模板代码以确保所有调用都有效。发现无效的来电,例如
    不支援的函式呼叫。


,我写了 -

template<typename T>
void foo( T x)
{
   some illegal text
}

int main()
{
   return 0;
}

它在Visual Studio 2010上构建得很好,但是,在gcc-4.3.4上失败了。哪一个符合C ++标准?是否强制模板代码即使使用模板实例化也可以编译?

It build fine on Visual Studio 2010 with out any warnings with optimizations turned off. How ever, it failed on gcc-4.3.4. Which one is complying to the C++ standard ? Is it mandatory for template code to get compiled even with out template instantiation ?

推荐答案

有问题的程序是错误的, C ++标准在这种情况下不需要诊断,因此Visual Studio和GCC都以兼容的方式运行。从C ++ 03标准的§14.6/ 7(强调我的):

The program in question is ill-formed, but the C++ standard does not require a diagnostic in this case, so both Visual Studio and GCC are behaving in a compliant fashion. From §14.6/7 of the C++03 standard (emphasis mine):


知道哪些名称是类型名称允许每个模板定义。对于可以生成有效专业化的模板定义,不应发布
诊断。 如果没有为模板定义生成
有效的专门化,并且该模板未实例化,则模板
定义不合格,无需诊断。
如果使用类型在非依赖名称中是不完整的
,在模板被定义但在完成实例化的时间点完成,
如果该类型的完整性影响是否程序格式良好或影响程序的语义
,程序是不成形的;不需要诊断。 [注意:如果模板被实例化,
错误将根据本标准中的其他规则进行诊断。正是当这些错误被诊断时
是一个实施质量问题。 ] [示例:

Knowing which names are type names allows the syntax of every template definition to be checked. No diagnostic shall be issued for a template definition for which a valid specialization can be generated. If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. If a type used in a non-dependent name is incomplete at the point at which a template is defined but is complete at the point at which an instantiation is done, and if the completeness of that type affects whether or not the program is well-formed or affects the semantics of the program, the program is ill-formed; no diagnostic is required. [Note: if a template is instantiated, errors will be diagnosed according to the other rules in this Standard. Exactly when these errors are diagnosed is a quality of implementation issue. ] [Example:

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
    }
};

- end example ]

这篇关于模板编译:gcc vs VS2010的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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