有没有一种简单的方法来判断一个类/ struct是否没有数据成员? [英] Is there an easy way to tell if a class/struct has no data members?
问题描述
Hallo,
在C ++中有一些简单的方法来告诉(在编译时)类/ struct是否没有数据成员?
例如 struct T {};
我的第一个想法是比较 sizeof = 0
,但这总是至少为1。
显然的答案是看看代码,
$ p您可以从另一个空类派生此类,并检查 sizeof (OtherClass)== 1
。 Boost在其 is_empty
类型特征中执行此操作。
未测试:
template< typename T>
struct is_empty {
struct helper_:T {int x; };
static bool const VALUE = sizeof(helper_)== sizeof(int);
};但是,这依赖于空的基类优化(但是所有现代编译器都这样做)。 p>
Hallo,
is there some easy way in C++ to tell (in compile-time) if a class/struct has no data members?
E.g. struct T{};
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.
解决方案 You can derive from this class in another empty and check whether sizeof(OtherClass) == 1
. Boost does this in its is_empty
type trait.
Untested:
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).
这篇关于有没有一种简单的方法来判断一个类/ struct是否没有数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!