Vin*_*ent 17 c++ noexcept c++11
考虑以下功能:
// 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;
Run Code Online (Sandbox Code Playgroud)
noexcept如果类型T不是可构造的,我想创建此函数.
怎么做 ?(我的意思是什么语法?)
Rei*_*ica 21
像这样:
#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);
Run Code Online (Sandbox Code Playgroud)
但另请参阅为什么模板只能在头文件中实现?.您(通常)无法在源文件中实现模板.
noexcept可以接受表达式,如果表达式的值为true,则声明该函数不会抛出任何异常.所以语法是:
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()))
{
}
Run Code Online (Sandbox Code Playgroud)
编辑:在std::is_nothrow_constructible<T>::value这种情况下,使用如下有点脏
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |