当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。