template boy
template boy

Reputation: 10480

Possible g++ bug with noexcept and templates

I get an error about mismatched noexcept specifications when I use templates in conjunction with the noexcept specifier. It compiles with various versions of clang I've used and fails in all versions of 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()
{
}

Error:

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()));
     ^

Is this a bug? Is there any way to get around it?

Upvotes: 4

Views: 201

Answers (1)

Jonesinator
Jonesinator

Reputation: 4216

Using an enum to store the result of the noexcept operator is one horrifying workaround at least in gcc-4.9.2 used currently by ideone.

#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;
}

Upvotes: 1

Related Questions