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


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

<type_traits>頭文件中提供了C++ STL的std::is_default_constructible模板。 C++ STL的std::is_default_constructible模板用於檢查T是否是默認可構造的。可以構造默認構造函數而沒有參數或初始化值。如果T是默認的可構造類型,則返回布爾值true,否則返回false。

頭文件:

#include<type_traits>

模板類別:

template <class T> 
struct is_default_constructible;

用法:

std::is_default_constructible>class T>::value

參數:模板std::is_default_constructible接受單個參數T(Trait類),以檢查T是否為默認的可構造類型。



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

  • True:如果類型T是默認可構造的。
  • False:如果類型T不是默認可構造的。

下麵是說明C /C++中的std::is_default_constructible模板的程序:

程序:

// C++ program to illustrate 
// std::is_default_constructible 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Declare structures 
struct A { 
}; 
  
struct B { 
    int n; 
    B() = default; 
}; 
  
// Class 
class classA { 
    ~classA() = delete; 
}; 
  
// Inherited class 
class classB:classA { 
}; 
  
// Driver Code 
int main() 
{ 
    cout << boolalpha; 
  
    // Check if int is default constructible? 
    cout << "int:"
         << is_default_constructible<int>::value 
         << endl; 
  
    // Check if struct A is default constructible? 
    cout << "struct A:"
         << is_default_constructible<A>::value 
         << endl; 
  
    // Check if struct B is default constructible? 
    cout << "struct B:"
         << is_default_constructible<B>::value 
         << endl; 
  
    // Check if classA is default constructible? 
    cout << "classA:"
         << is_default_constructible<classA>::value 
         << endl; 
  
    // Check if classB is default constructible? 
    cout << "classB:"
         << is_default_constructible<classB>::value 
         << endl; 
  
    return 0; 
}
輸出:
int:true
struct A:true
struct B:true
classA:false
classB:false

參考: http://www.cplusplus.com/reference/type_traits/is_default_constructible/




相關用法


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