C++ 中的 std::is_abstract 模板
在本文中,我們將討論 C++ STL 中 std::is_abstract 模板的工作原理、語法和示例。
Is_abstract 模板有助於檢查類是否為抽象類。
什麼是抽象類?
抽象類是指至少包含一個純虛擬函式的類。我們使用抽象類是因為當我們定義函式時,我們不知道其實現,因此當我們不知道類的函式應該進一步做什麼時,它非常有用,但我們確定我們的系統中必須存在這樣的函式。因此,我們宣告一個純虛擬函式,它只宣告而不包含該函式的實現。
因此,當我們想從類的例項中檢查該類是否為抽象類時,我們使用 is_abstract()。
is_abstract() 繼承自 itegral_constant 並返回 true_type 或 false_type,具體取決於類 T 的例項是否為多型類型別。
語法
template <class T> struct is_abstract;
引數
此模板只能有一個引數 T,該引數為類型別,用於檢查類 T 是否為抽象類。
返回值
此函式返回布林型別值,true 或 false。
如果 T 是抽象類,則返回 true;如果 T 不是抽象類,則返回 false。
示例
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 {
int var;
};
struct TP_2 {
virtual void dummy() = 0;
};
class TP_3 : TP_2 {
};
int main() {
cout << boolalpha;
cout << "checking for is_abstract: ";
cout << "\nstructure TP_1 with one variable :"<< is_abstract<TP_1>::value;
cout << "\nstructure TP_2 with one virtual variable : "<< is_abstract<TP_2>::value;
cout << "\nclass TP_3 which is derived from TP_2 structure : "<< is_abstract<TP_3>::value;
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出:
checking for is_abstract: structure TP_1 with one variable : false structure TP_2 with one virtual variable : true class TP_3 which is derived from TP_2 structure : true
示例
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 {
virtual void dummy() = 0;
};
class TP_2 {
virtual void dummy() = 0;
};
struct TP_3 : TP_2 {
};
int main() {
cout << boolalpha;
cout << "checking for is_abstract: ";
cout << "\nstructure TP_1 with one virtual function :"<< is_abstract<TP_1>::value;
cout << "\nclass TP_2 with one virtual function : "<< is_abstract<TP_2>::value;
cout << "\nstructure TP_3 which is derived from TP_2 class : "<< is_abstract<TP_3>::value;
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出:
checking for is_abstract: structure TP_1 with one virtual function : true class TP_2 with one virtual function : true structure TP_3 which is derived from TP_2 class : true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP