首页 > 解决方案 > 类/结构内的递归 noexcept 规范

问题描述

跟进问题Recursive noexcept specification。如果我在类或结构范围内声明函数f,它应该在类/结构范围内的任何地方都可见。同样在 noexcept 说明符中(如果它是递归调用则无关紧要)。MSVC v19.28 和 Clang 12.0.1 接受并编译此代码,但 GCC 11.2 不接受?为什么?它是 GCC 编译器还是 MSVC 和 Clang 中的错误?

struct S {

    template<typename T>
    static auto f(T && t) noexcept {
        return true;
    }

    template<typename T, typename... Ts>
    static auto f(T && t, Ts && ... ts) noexcept(noexcept(f(ts...))) {
        return f(ts...);
    }

};

int main() {
    S::f(true, 0, 5u);
}

GCC 错误信息:

In instantiation of 'static auto S::f(T&&, Ts&& ...) [with T = bool; Ts 
= {int, unsigned int}]':
error: no matching function for call to 'S::f(int&, unsigned int&)'
    static auto f(T && t, Ts && ... ts) noexcept(noexcept(f(ts...))) {
                                                          ~^~~~~~~
note: candidate: 'template<class T> static auto S::f(T&&)'
    static auto f(T && t) noexcept {
                ^
note:   template argument deduction/substitution failed:
note:   candidate expects 1 argument, 2 provided
    static auto f(T && t, Ts && ... ts) noexcept(noexcept(f(ts...))) {
                                                          ~^~~~~~~

标签: c++gccclang

解决方案


我相信这是 GCC 8 中引入的一个 GCC 错误。正如您在此处看到的,使用 GCC 7.5 编译时,一切都编译成功。

为什么要编译成功?

因为noexcept仅在需要时才实例化函数模板特化的 - 说明符。


推荐阅读