gpt4 book ai didi

c++ - 模板编译: gcc vs VS2010

转载 作者:行者123 更新时间:2023-11-30 00:38:35 28 4
gpt4 key购买 nike

摘自 David, Nicolai 的《C++ 模板:完整指南》一书

Thus, templates are compiled twice:

  1. Without instantiation, the template code itself is checked for correct syntax. Syntax errors are discovered, such as missing semicolons.
  2. At the time of instantiation, the template code is checked to ensure that all calls are valid. Invalid calls are discovered, such as unsupported function calls.

保持第一点,我写了-

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

int main()
{
return 0;
}

在关闭优化的情况下,它在 Visual Studio 2010 上构建良好,没有任何警告。怎么过,it failed on gcc-4.3.4 .哪一个符合 C++ 标准?即使没有模板实例化,模板代码是否也必须编译?

最佳答案

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

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]

关于c++ - 模板编译: gcc vs VS2010,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323980/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com