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 次浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.