考虑以下函数:
// 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;
noexcept如果类型T不可构造,我想创建这个函数。
怎么做 ?(我的意思是语法是什么?)
像这样:
#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);
但也请看为什么模板只能在头文件中实现?. 您(通常)无法在源文件中实现模板。
noexcept可以接受一个表达式,如果表达式的值为真,则该函数被声明为不抛出任何异常。所以语法是:
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()))
{
}
编辑:在std::is_nothrow_constructible<T>::value这种情况下,使用如下方式不太脏