19

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

Vincent
  • 57,703
  • 61
  • 205
  • 388
  • 2
    you may check with `std::is_nothrow_constructible` – Jarod42 Dec 30 '13 at 10:33
  • I know but I never used the noexcept keyword before, so I wonder what the syntax is. – Vincent Dec 30 '13 at 10:34
  • nothrow constructible from what arguments? The answers assume you mean nothrow *default* constructible a la `T foo;`, but with the function taking a universal reference I wonder if you mean nothrow constructible from the function argument a la `T foo{std::forward(x)};`. – Casey Dec 30 '13 at 14:04

2 Answers2

23

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.

Community
  • 1
  • 1
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
7

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

Davidbrcz
  • 2,335
  • 18
  • 27
  • Technically `noexcept(noexcept(T()))` *does not* mean `T` can be constructed without exception; it means `T` can be constructed *and destructed* without exception. You need to use `noexcept(noexcept(::new (nullptr) T()))`. – Zizheng Tai Jul 18 '16 at 22:25