在下面的代码中,变量定义 B<int, int>(14); 应该是错误的:

#include <iostream>

struct A {
};

template<class T, class R=A>
class B {
public:
    explicit B(const int s, R n = A()) {
        std::cout << "c\n";
    }
};

template <class T, class R=A>
void foo(const int s, R nx = A()) {};

int main() {
    B<int, int>(14);
    // foo<int, int>(14);
    // error: could not convert ‘A()’ from ‘A’ to ‘int’
}

为什么它不会导致编译错误?

compiled 使用 gcc 7.3 和 g++ -std=c++17 的代码

当我使用 gcc 7.3 和 g++ -std=c++14 编译代码时,出现错误。

我认为该行在 n 的构造函数中使用参数 B 的默认值。
n 的默认值是 A() ,它不能转换为 int

我应该得到一个编译错误。但事实并非如此。

函数的类似情况(由 foo 测试)会导致编译错误。

最佳答案

您遇到了 GCC bug #83020 。 Clang 6 和 GCC 8(以及 GCC 6)正确拒绝您的示例代码,就像 C++14 模式下的 GCC 7 一样。

关于c++ - 具有错误类型默认值的构造函数不会引发 GCC 7 错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50299607/

10-12 00:33
查看更多