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 ?)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With