Vincent
Vincent

Reputation: 60451

Use of the noexcept specifier in function declaration and definition?

Consider the following function:

// Declaration in the .h file
class MyClass
{
    template <class T> void function(T&& x) const;
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) const;

I want to make this function noexcept if the type T is nothrow constructible.

How to do that ? (I mean what is the syntax ?)

Upvotes: 19

Views: 7529

Answers (2)

Davidbrcz
Davidbrcz

Reputation: 2397

noexcept can accept an expression and if the value of the expression is true, the function is declared to not throw any exceptions. So the syntax is :

class MyClass
{
template <class T> void function(T&& x) noexcept (noexcept(T()));
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) noexcept (noexcept(T()))
{

}

Edit : the use of std::is_nothrow_constructible<T>::value as below is a bit less dirty i that case

Upvotes: 7

Like this:

#include <type_traits>

// Declaration in the .h file
class MyClass
{
    public:
    template <class T> void function(T&& x) noexcept(std::is_nothrow_constructible<T>::value);
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) noexcept(std::is_nothrow_constructible<T>::value);

Live example

But please also see Why can templates only be implemented in the header file?. You (generally) cannot implement a template in the source file.

Upvotes: 23

Related Questions