C++ 中的 is_empty 模板
在本文中,我們將討論 C++ STL 中 std::is_empty 模板的工作原理、語法和示例。
is_empty 是一個屬於 當類中沒有儲存資料時,該類被稱為空類。空類滿足以下條件: 該模板只能有一個類 T 的引數,並檢查類 T 是否為空類。 如果給定的型別為空類,則返回布林值 true;如果給定的型別不是空類,則返回 false。 如果執行上述程式碼,它將生成以下輸出: 如果執行上述程式碼,它將生成以下輸出:什麼是空類?
語法
template <class T>is_empty;
引數
返回值
示例
Input: class A{};
is_empty<A>::value;
Output: true
Input: class B{ void fun() {} };
is_empty<B>::value;
Output: true
示例
#include <iostream>
#include <type_traits>
using namespace std;
class TP_1 {
};
class TP_2 {
int var;
};
class TP_3 {
static int var;
};
class TP_4 {
~TP_4();
};
int main() {
cout << boolalpha;
cout << "checking for is_empty template for a class with no variable: "<< is_empty<TP_1>::value;
cout <<"\nchecking for is_empty template for a class with one variable: "<< is_empty<TP_2>::value;
cout <<"\nchecking for is_empty template for a class with one static variable: "<< is_empty<TP_3>::value;
cout <<"\nchecking for is_empty template for a class with constructor: "<< is_empty<TP_4>::value;
return 0;
}
輸出
checking for is_empty template for a class with no variable: true
checking for is_empty template for a class with one variable: false
checking for is_empty template for a class with one static variable: true
checking for is_empty template for a class with constructor: true
示例
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 {
};
struct TP_2 {
int var;
};
struct TP_3 {
static int var;
};
struct TP_4 {
~TP_4();
};
int main() {
cout << boolalpha;
cout << "checking for is_empty template for a structure with no variable: "<< is_empty<TP_1>::value;
cout <<"\nchecking for is_empty template for a structure with one variable: "<< is_empty<TP_2>::value;
cout <<"\nchecking for is_empty template for a structure with one static variable: "<< is_empty<TP_3>::value;
cout <<"\nchecking for is_empty template for a structure with constructor: "<< is_empty<TP_4>::value;
return 0;
}
輸出
checking for is_empty template for a structure with no variable: true
checking for is_empty template for a structure with one variable: false
checking for is_empty template for a structure with one static variable: true
checking for is_empty template for a structure with constructor: true