在C++中std::is_nothrow_default_constructible及示例
C++ STL中的 std::is_nothrow_default_constructible 模板存在于 < type_traits>头文件中。 C++ STL中的 std::is_nothrow_default_constructible 模板用于检查给定类型 T 是否为默认可构造类型,而且其不会引发任何异常。如果 T 是默认可构造类型,则返回布尔值true;否则返回false。
头文件:
include < type_traits >
模板类:
template <class T>
struct is_nothrow_default_constructible;
语法:
std::is_nothrow_default_constructible::value
参数: 模板 std::is_nothrow_default_constructible 只接受一个参数 T(Trait class) ,以检查 T 是否为默认可构造类型。
返回值: 此模板返回布尔变量,如下所示:
- 真:如果类型 T 是不抛出任何异常构造的。
 - 假:如果类型 T 不是不抛出异常构造的。
 
以下是C/C++中展示 std::is_nothrow_default_constructible 模板的程序:
程序1:
// C++程序演示
// std::is_nothrow_default_constructible
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
  
// 声明结构
struct X {
    X(int, float){};
};
  
struct Y {
    Y(const Y&) {}
};
  
struct Z {
    int n;
    Z() = default;
};
  
// 驱动程序
int main()
{
  
    cout << boolalpha;
  
    // 检查是否int不抛出默认构造
    // 或不是可构造
    cout << "int: "
         << is_nothrow_default_constructible<int>::value
         << endl;
  
    // 检查是否struct X不抛出默认构造
    // 或不是可构造
    cout << "struct X: "
         << is_nothrow_default_constructible<X>::value
         << endl;
  
    // 检查是否struct Y不抛出默认构造
    // 或不是可构造
    cout << "struct Y: "
         << is_nothrow_default_constructible<Y>::value
         << endl;
  
    // 检查是否struct Z不抛出默认构造
    // 或不是可构造
    cout << "struct Z: "
         << is_nothrow_default_constructible<Z>::value
         << endl;
  
    // 检查X(int, float)的构造函数是否
    // 不会抛出默认构造异常
    cout << "constructor X(int, float): "
         << is_nothrow_default_constructible<X(int, float)>::value
         << endl;
    return 0;
}
int: true
struct X: false
struct Y: false
struct Z: true
constructor X(int, float): false
参考资料: http://www.cplusplus.com/reference/type_traits/is_nothrow_default_constructible/
极客教程