在C++中std::is_trivially_constructible的例子
C++ STL中的 std::is_trivially_constructible 模板位于 < type_traits>头文件中。C ++ STL的 std::is_trivially_constructible 模板用于检查给定类型 T 是否具有一组参数的平凡构造类型。如果T是平凡构造类型,则返回布尔值true,否则返回false。
头文件:
#include <type_traits>
模板类:
template <class T, class.. Args>
struct is_trivially_constructible;
语法:
std::is_trivially_constructible::value
参数: 模板 std::is_trivially_constructible 接受两个参数:
- T: 一个数据类型或未知大小的数组。
 - Args: 构造函数形式的参数类型列表,其顺序与构造函数中的顺序相同。
 
返回值: 此模板返回布尔变量,如下所示:
- True:如果类型 T 是平凡的可构造型类型。
 - False:如果类型 T 不是平凡的可构造类型。
 
以下是在C / C++中使用 std::is_trivially_constructible 模板的程序示例:
程序1:
// C++ program to illustrate
// std::is_trivially_constructible
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
  
// Declare structures
struct Ex1 {
    std::string str;
};
struct Ex2 {
    int n;
    Ex2() = default;
};
  
struct A {
  
    // Constructor
    A(int, int){};
};
  
// Driver Code
int main()
{
    cout << boolalpha;
  
    // Check if Ex1 is a trivally
    // constructible or not
    cout << "Ex1: "
         << is_trivially_constructible<Ex1>::value
         << endl;
  
    // Check if struct Ex2 is a trivally
    // constructible or not
    cout << "Ex2: "
         << is_trivially_constructible<Ex2>::value
         << endl;
  
    // Check if A(int, float) is a trivally
    // constructible or not
    cout << "A(int, int): "
         << is_trivially_constructible<A(int, int)>::value
         << endl;
    return 0;
}
Ex1: false
Ex2: true
A(int, int): false
程序2:
// C++ 程序演示
// std::is_trivially_constructible
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
  
// 定义结构体
struct X {
};
  
struct Y {
  
    // 默认构造函数
    Y() {}
  
    // 有参数构造函数
    Y(const X&)
    noexcept {}
};
  
// 主函数
int main()
{
    cout << boolalpha;
  
    // 检查 int 是否可以平凡构造
    // 或者不能平凡构造
    cout << "int(): "
         << is_trivially_constructible<int>::value
         << endl;
  
    // 检查结构体 Y 是否可平凡构造
    cout << "Y(): "
         << is_trivially_constructible<Y>::value
         << endl;
  
    // 检查结构体 Y 是否可以使用X构造
    // 平凡构造或者非平凡构造
    cout << "Y(X): "
         << is_trivially_constructible<Y, X>::value
         << endl;
  
    return 0;
}
int(): true
Y(): false
Y(X): false
参考: http://www.cplusplus.com/reference/type_traits/is_trivially_constructible/
极客教程