Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?)

like image 703
Vincent Avatar asked Dec 30 '13 10:12

Vincent


People also ask

What is the use of Noexcept?

The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.

What does Noexcept mean in C++?

A noexcept-expression is a kind of exception specification: a suffix to a function declaration that represents a set of types that might be matched by an exception handler for any exception that exits a function.

What happens when Noexcept function throws?

If you throw, your program terminates What happens if you throw from a noexcept function? Your program terminates, and may or may not unwind the stack. Terminating program isn't the nicest way to report an error to your user. You would be surprised that most of C++ code might throw.

Is Noexcept required?

Explicit instantiations may use the noexcept specifier, but it is not required. If used, the exception specification must be the same as for all other declarations.


1 Answers

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.

like image 70
Angew is no longer proud of SO Avatar answered Oct 14 '22 03:10

Angew is no longer proud of SO