有没有一种简单的方法可以判断一个类/结构是否没有数据成员?

编程入门 行业动态 更新时间:2024-10-04 17:31:39
本文介绍了有没有一种简单的方法可以判断一个类/结构是否没有数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好,

在 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:en.cppreference/w/cpp/types/is_empty

Since C++11, you can use standard std::is_empty trait: en.cppreference/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).

更多推荐

有没有一种简单的方法可以判断一个类/结构是否没有数据成员?

本文发布于:2023-11-29 02:08:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644871.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:成员   结构   简单   方法   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!