可能的 g++ 错误与 noexcept 和模板

Possible g++ bug with noexcept and templates

本文关键字:noexcept 错误 g++      更新时间:2023-10-16
当我

将模板与noexcept说明符结合使用时,我收到有关不匹配的noexcept 规范的错误。它使用我使用过的各种版本的 clang 进行编译,并且在所有版本的 gcc 中都失败。

struct Y
{
    void h();
};
template<typename T>
struct X
{
    void f() noexcept(noexcept(std::declval<Y>().h()));
};
template<typename T>
void X<T>::f() noexcept(noexcept(std::declval<Y>().h()))
{
}
int main()
{
}

错误:

g++ -std=c++1y -O2 -Wall -pthread main.cpp && ./a.out
main.cpp:15:56: error: declaration of 'void X<T>::f() noexcept (noexcept (declval<Y>().Y::f()))' has a different exception specifier
void X<T>::f() noexcept(noexcept(std::declval<Y>().f()))
                                                    ^
main.cpp:11:10: error: from previous declaration 'void X<T>::f() noexcept (noexcept (declval<Y>().Y::f()))'
void f() noexcept(noexcept(std::declval<Y>().f()));
     ^

这是一个错误吗?有什么办法可以绕过它吗?

使用枚举来存储 noexcept 运算符的结果至少在 ideone 当前使用的 gcc-4.9.2 中是一种可怕的解决方法。

#include <iostream>
#include <utility>
struct Y
{
    void h() noexcept;
    void i();
};
enum Y_noexcept_value
{
    h = noexcept(std::declval<Y>().h()),
    i = noexcept(std::declval<Y>().i())
};
template<typename T>
struct X
{
    void f() noexcept(Y_noexcept_value::h);
    void g() noexcept(Y_noexcept_value::i);
};
template<typename T>
void X<T>::f() noexcept(Y_noexcept_value::h)
{
}
template<typename T>
void X<T>::g() noexcept(Y_noexcept_value::i)
{
}
int main()
{
    std::cout << std::boolalpha
              << noexcept(std::declval<X<int>>().f()) << std::endl
              << noexcept(std::declval<X<int>>().g()) << std::endl;
    return 0;
}