C++ 中的 is_empty 模板


在本文中,我們將討論 C++ STL 中 std::is_empty 模板的工作原理、語法和示例。

is_empty 是一個屬於

什麼是空類?

當類中沒有儲存資料時,該類被稱為空類。空類滿足以下條件:

  • 除長度為 0 的位域外,不得有非靜態成員。
  • 不得有虛基類或虛擬函式。
  • 不得有基類。

語法

template <class T>is_empty;

引數

該模板只能有一個類 T 的引數,並檢查類 T 是否為空類。

返回值

如果給定的型別為空類,則返回布林值 true;如果給定的型別不是空類,則返回 false。

示例

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

更新於: 2020 年 3 月 23 日

210 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告