【问题标题】:GCC template argument deduction/substitution failedGCC 模板参数扣除/替换失败
【发布时间】:2019-09-11 17:05:24
【问题描述】:

下面的代码在 MSVC 上编译,但在 GCC (4.6.3) 上失败。为什么会失败,我应该如何解决?

#include <array>

class Foo {
public:
    template<typename T, int N>
    operator std::array<T, N>() const {
        return std::array<T, N>();
    }
};

int main(){
    Foo val;

    // both of the following lines fail on GCC with error:
    //    "no matching function call...", ultimately with a note:
    //    "template argument deduction/substitution failed"
    auto a = val.operator std::array<int, 2>();
    static_cast<std::array<int, 2>>(val);

    return 0;
}

编辑:尽管为std::array 的模板参数传递了int,但以下代码确实可以编译(在两个编译器上)。

template<int N, typename T>
struct Bar {
    std::array<T, N> buf;
};

int main()
{
    auto x = Bar<3, double>();
    return 0;
}

【问题讨论】:

    标签: c++ templates gcc compiler-errors c++14


    【解决方案1】:

    如果您阅读收到的错误消息的全文,编译器会抱怨,因为您的模板类中N 的类型是int,而std::array 的第二个参数是std::size_t,即是您系统上的unsigned long

    将模板的声明更改为使用std::size_t N 将解决问题。

    MSVC 没有抱怨可能是因为它认识到值“2”适用于任何一种情况,或者因为编译器错误。

    【讨论】:

    • clang 和 gcc 都接受this,所以看起来更像是他们这边的一个错误。
    • @1201ProgramAlarm 我也想知道,但是为什么第二个代码片段(在我的问题的编辑中)编译时不会出错?
    • 对于 MSVC,这是我们编译器中的一个错误。我们已经打开了一个内部问题来跟踪它,谢谢!
    猜你喜欢
    • 2013-06-20
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多