Search code examples
c++templatesnoexcept

Mark function as noexcept based on template argument


Take this code:

template <class T>
void my_func() { T::some_method(); }

int main() {
    std::cout << (noexcept(my_func<SomeClass>()) ? "noexcept" : "can throw") << std::endl;
    return 0;
}

This will always print out that my_func() can throw, even if SomeClass::some_method() is marked as noexcept. (at least with gcc 7.4.0 and -std=c++17)

Is there a practical way to make the compiler detect if the function is noexcept or not depending on the template argument ?

The only one that I can think of is using std::enable_if :

template <class T>
std::enable_if_t<true == noexcept(T::some_method())>
my_func() noexcept { T::some_method(); }

template <class T>
std::enable_if_t<false == noexcept(T::some_method())>
my_func() { T::some_method(); }

But it takes a lot of space and causes code repetition.


Solution

  • noexcept specifications have a version taking a boolean.

    template <class T>
    void my_func() noexcept(noexcept(T::some_method())) { T::some_method(); }
    

    Now it will be conditionally noexcept, based on the expression T::some_method().