代码之家  ›  专栏  ›  技术社区  ›  R zu

默认值类型错误的构造函数不会对GCC 7产生错误

  •  4
  • R zu  · 技术社区  · 6 年前

    在以下代码中,变量定义 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 )将导致编译错误。

    1 回复  |  直到 6 年前
        1
  •  6
  •   hlt    6 年前

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