<type_traits>頭文件中提供了C++ STL的std::is_base_of模板。 C++ STL的std::is_base_of模板用於檢查Base類是否為Derived類的基類。根據上述條件,它返回布爾值true或false。
頭文件:
#include<type_traits>
模板類別:
template <class Base, class Derived>
struct is_base_of;
用法:
std::is_base_of<A, B>::value
參數:它接受以下兩個類作為參數:
- A類(作為基類):它代表基類。
- B類(作為派生類):它代表派生類。
返回值:該模板返回一個布爾變量,如下所示:
- True:如果基類(類A)是派生類(類B)的父級。
- False:如果基類(類A)不是派生類(類B)的父級。
以下示例程序旨在說明C /C++中的std::is_base_of模板:
程序1:
// C++ program to demonstrate the
// std::is_base_of templates
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
// Base class A
class A {
};
// Derived Class B
class B:A {
};
// Class C
class C {
};
// Driver Code
int main()
{
cout << boolalpha;
// Check if class A is a base class
// of class B
cout << "A is base class of B:"
<< is_base_of<A, B>::value
<< endl;
// Check if class B is a base class
// of class A
cout << "B is base class of A:"
<< is_base_of<B, A>::value
<< endl;
// Check if class C is a base class
// of class B
cout << "C is base class of B:"
<< is_base_of<C, B>::value
<< endl;
// Check if class C is a base class
// of class C
cout << "C is base class of C:"
<< is_base_of<C, C>::value
<< endl;
return 0;
}
輸出:
A is base class of B:true B is base class of A:false C is base class of B:false C is base class of C:true
參考: http://www.cplusplus.com/reference/type_traits/is_base_of/
相關用法
- C++ std::is_assignable模板用法及代碼示例
- C++ std::is_function模板用法及代碼示例
- C++ std::is_convertible模板用法及代碼示例
- C++ std::is_constructible模板用法及代碼示例
- C++ std::is_member_object_pointer模板用法及代碼示例
- C++ std::is_trivially_copyable模板用法及代碼示例
- C++ std::is_same模板用法及代碼示例
- C++ std::is_member_function_pointer模板用法及代碼示例
- C++ is_rvalue_reference用法及代碼示例
- C++ is_fundamental用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 std::is_base_of template in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。