I try to check template class T in function do_math() on the possibility of throwing an exception in the copy assignment operator.
But the following code throws an error:
template<class T>
void do_math()
noexcept(noexcept(T(std::declval<T>())) && noexcept(std::declval<T>() + std::declval<T>()) && noexcept(std::declval<T>().operator = (std::declval<T>())) )
{
}
main.cpp:9:135: error: request for member ‘operator=’ in ‘std::declval<int>()’, which is of non-class type ‘int’
noexcept(noexcept(T(std::declval<T>())) && noexcept(std::declval<T>() + std::declval<T>()) && noexcept(std::declval<T>().operator = (std::declval<T>())) )
~~~~~~~~~~~~~~~~~~~~~~~~~~~^
Please help me to write the correct check.
You don't need to write this yourself. There is already a type trait for it in the standard library:
and then
gives you
true/falseand can be used in thenoexceptspecifier.Similarly there is
to check whether non-throwing copy construction is possible.
Note however that if
Tis not a lvalue reference type, thenstd::declval<T>is a rvalue, not a lvalue. Therefore your current code is testing for move constructibility, not copy constructibility. (There are analogous type traits for these as well.)