c++ - 未使用的模板方法中的错误

标签 c++ templates gcc clang non-static

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/

相关文章:

c++ - 在 C++11 中从 C++17 重新实现 std::map::try_emplace()?

c++ - 具有不同返回类型的成员函数的模板化别名

c++ - uintX_t 和 intX_t 类型的打印保证

c++ - GCC 模板问题

gcc - 使用弱符号时如何避免对 GLIBC_X.Y 的依赖

c++ - window C++ |写入文件时,什么负责将\n 转换为\r\n?

c++ - 为什么随机分布不将引擎作为模板参数?

C++:返回类型为 T 且不采用 T 类型参数的模板函数将无法编译

c++ - 使用 AVX 异或两个 zmm(512 位)寄存器

c - 没有成员编译错误