获取一个类中的字段数 [英] get the number of fields in a class
问题描述
是否可以获取类的字段数?
Is there a way to get the number of fields of a class?
struct Base {
char a;
int b;
};
struct Derived : Base {
std::string c;
};
static_assert(num_fields<Base>::value == 2);
static_assert(num_fields<Derived>::value == 1);
我发现这个问题,但是它已经过时了-我希望可以将某些东西与C ++ 14/17结合在一起(毕竟我们现在有了类似 magic_get -也许是其中的一个子集...?)
I've found this question but it is very dated - I am hoping something can be stitched together with C++14/17 (after all we now have something like magic_get - perhaps some subset from it...?)
编辑:-即使仅适用于MSVC或GCC或Clang,编译器挂钩也将起作用-我全部使用了3。
- a compiler hook would also work even if it's only for MSVC or GCC or Clang - I use all 3.
推荐答案
实际上是安东尼Polukhin向我们展示了自C ++ 14起,C ++ 确实具有(某种)反射;并且您可以提取有关字段的信息。 ...至少对于普通旧数据结构/类而言。观看他的CppCon 2016演讲:
Indeed, Antony Polukhin has shown us that C++ does have (some) reflection, since C++14, without knowing it; and that you can extract information about the fields. ... well, at least for plain-old-data structs/classes. Watch his CppCon 2016 talk:
C ++ 14思考如果没有宏,标记或外部工具/ Antony Polukhin
然后使用:
template <class T>
constexpr std::size_t fields_count() noexcept;
这可以使您获得字段计数。要使用它,您需要以下两个文件:
which gets you the field count. To use that you need these two file:
> https://github.com/apolukhin/magic_get/blob/develop/include/boost/pfr/detail/config.hpp
https://github.com/apolukhin/magic_get/ blob / develop / include / boost / pfr / detail / fields_count.hpp
,就足够了。
这篇关于获取一个类中的字段数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!