Is there an easy way to tell if a class/struct has no data members?(有没有一种简单的方法可以判断一个类/结构是否没有数据成员?)
问题描述
你好,
在 C++ 中是否有一些简单的方法来判断(在编译时)一个类/结构是否没有数据成员?
is there some easy way in C++ to tell (in compile-time) if a class/struct has no data members?
例如struct T{};
我的第一个想法是比较 sizeof(T)==0,但这似乎总是至少为 1.
My first thought was to compare sizeof(T)==0, but this always seems to be at least 1.
显而易见的答案是只看代码,但我想打开它.
The obvious answer would be to just look at the code, but I would like to switch on this.
推荐答案
从 C++11 开始,您可以使用标准的 std::is_empty trait:https://en.cppreference.com/w/cpp/types/is_empty
Since C++11, you can use standard std::is_empty trait: https://en.cppreference.com/w/cpp/types/is_empty
如果您正在使用旧式编译器,有一个技巧:您可以从另一个空的类中派生并检查是否 sizeof(OtherClass) == 1.Boost 在它的 is_empty 类型特征中做到了这一点.
If you are on paleo-compiler diet, there is a trick: you can derive from this class in another empty and check whether sizeof(OtherClass) == 1. Boost does this in its is_empty type trait.
未经测试:
template <typename T>
struct is_empty {
struct helper_ : T { int x; };
static bool const VALUE = sizeof(helper_) == sizeof(int);
};
然而,这依赖于空基类优化(但所有现代编译器都这样做).
However, this relies on the empty base class optimization (but all modern compilers do this).
这篇关于有没有一种简单的方法可以判断一个类/结构是否没有数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有一种简单的方法可以判断一个类/结构是否没有数据成员?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
