struct B
{
int a;
void foo() {a = 5;}
};
template <typename T>
struct A
{
A(int i) { B::foo(); }
A(double d) {}
};
int main()
{
A<int> a(5.0);
}
gcc 4.7.2 编译它没有错误。 clang 3.4svn 提示:
$ clang -Wall -Wextra test.cpp
test.cpp:10:16: error: call to non-static member function without an object argument
A(int i) { B::foo(); }
~~~^~~
代码当然是错误的,但是哪个编译器是符合标准的呢?
同样奇怪的是,如果您使用 5 而不是 5.0,clang 不会像 gcc 那样打印任何“in instantiation”注释:
$ gcc test.cpp
test.cpp: In instantiation of ‘A<T>::A(int) [with T = int]’:
test.cpp:15:12: required from here
test.cpp:9:13: error: cannot call member function ‘void B::foo()’ without object
最佳答案
您的程序不正确,并且两个编译器都是正确的,因为该标准不需要符合标准的编译器进行诊断(让 gcc 忽略它)。没有有效实例化(标准术语中的特化)的模板是不正确的,即使该模板从未实例化也是如此。
在您的例子中,名称 B::foo()
里面A<T>::A(int)
是一个非依赖名称,所以需要在第一阶段查找时解析,只能引用B
上面定义的类。因为它不是 static
成员函数,但是一个非静态的,代码不正确,与类型无关T
用于实例化 A<T>
模板和程序格式错误。
相关引自14.6 [temp.res]/8:
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.
关于c++ - 未使用的模板方法中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17598699/