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


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


C++ STL的std::has_virtual_destructor用於檢查給定的類型T是否具有虛構的析構函數。它返回布爾值true或false。以下是相同的語法:

頭文件:

#include<type_traits>

用法:

template
  <class T>
  struct has_virtual_destructor;

參數:模板std::has_virtual_destructor接受單個參數T(Trait類)以檢查T是否具有虛擬析構函數。

返回值:



  • 正確:如果存在虛擬析構函數。
  • False:如果虛擬析構函數不存在。

以下示例程序旨在說明C++ STL中的std::has_virtual_destructor模板:

程序1:

// C++ program to illustrate 
// has_virtual_destructor example 
  
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
struct gfg1 { 
}; 
struct gfg2 { 
    virtual ~gfg2() {} 
}; 
struct gfg3:gfg2 { 
}; 
  
// Driver Code 
int main() 
{ 
    cout << boolalpha; 
    cout << "has_virtual_destructor:"
         << endl; 
    cout << "int:"
         << has_virtual_destructor<int>::value 
         << endl; 
    cout << "gfg1:"
         << has_virtual_destructor<gfg1>::value 
         << endl; 
    cout << "gfg2:"
         << has_virtual_destructor<gfg2>::value 
         << endl; 
    cout << "gfg3:"
         << has_virtual_destructor<gfg3>::value 
         << endl; 
  
    return 0; 
}
輸出:
has_virtual_destructor:
int:false
gfg1:false
gfg2:true
gfg3:true

程序2:

// C++ program to illustrate 
// has_virtual_destructor example 
  
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
struct gfg1 { 
    virtual ~gfg1() {} 
}; 
struct gfg2 { 
}; 
struct gfg3:gfg1 { 
}; 
  
// Driver Code 
int main() 
{ 
    cout << boolalpha; 
    cout << "has_virtual_destructor:"
         << endl; 
    cout << "int:"
         << has_virtual_destructor<int>::value 
         << endl; 
    cout << "gfg1:"
         << has_virtual_destructor<gfg1>::value 
         << endl; 
    cout << "gfg2:"
         << has_virtual_destructor<gfg2>::value 
         << endl; 
    cout << "gfg3:"
         << has_virtual_destructor<gfg3>::value 
         << endl; 
  
    return 0; 
}
輸出:
has_virtual_destructor:
int:false
gfg1:true
gfg2:false
gfg3:true

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




相關用法


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