當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std::is_trivially_constructible用法及代碼示例

<type_traits>頭文件中提供了C++ STL的std::is_trivially_constructible模板。 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:代表構造函數形式的參數類型的數據類型列表,其順序與構造函數相同。

返回值:該模板返回一個布爾變量,如下所示:

  • 正確:如果類型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++ program to illustrate 
// std::is_trivially_constructible 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Declare structures 
struct X { 
}; 
  
struct Y { 
  
    // Default Constructor 
    Y() {} 
  
    // Parameterized Constructor 
    Y(const X&) 
    noexcept {} 
}; 
  
// Driver Code 
int main() 
{ 
    cout << boolalpha; 
  
    // Check if int is a trivally 
    // constructible or not 
    cout << "int():"
         << is_trivially_constructible<int>::value 
         << endl; 
  
    // Check if struct Y is a trivally 
    // constructible or not 
    cout << "Y():"
         << is_trivially_constructible<Y>::value 
         << endl; 
  
    // Check if Y(X) is a trivally 
    // constructible or not 
    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/




相關用法


注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 std::is_trivially_constructible in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。