获取类中的字段数

onq*_*tam 7 c++ templates type-traits template-meta-programming c++11

有没有办法获得一个类的字段数?

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);
Run Code Online (Sandbox Code Playgroud)

我发现了这个问题,但它已经过时了 - 我希望可以用C++ 14/17拼接一些东西(毕竟我们现在有类似magic_get的东西- 可能是它的一些子集......?)

编辑: - 编译器钩子也可以工作,即使它只适用于MSVC或GCC或Clang - 我使用全部3.

ein*_*ica 7

事实上,Antony Polukhin告诉我们C++ 确实有(某些)反射,因为C++ 14,不知道它; 并且您可以提取有关字段的信息.......好吧,至少对于普通的数据结构/类.观看他的CppCon 2016演讲:

C++ 14没有宏,标记或外部工具的反射/ Antony Polukhin

然后你写:

template <class T, std::size_t I0, std::size_t... I>
constexpr auto detect_fields_count(std::size_t& out, std::index_sequence<I0, I...>)
    -> decltype( T{ ubiq_constructor<I0>{}, ubiq_constructor<I>{}... } )
{ out = sizeof...(I) + 1;      /*...*/ }

template <class T, std::size_t... I>
constexpr void detect_fields_count(std::size_t& out, std::index_sequence<I...>) {
    detect_fields_count<T>(out, std::make_index_sequence<sizeof...(I) - 1>{});
}
Run Code Online (Sandbox Code Playgroud)

这会让你获得实地数量.当然,你还需要巧妙构思的 ubiq结构.你真正需要使用的是这两个文件:

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

这应该足够了.


Ron*_*Ron 6

你不能这样做(开箱即用)因为C++中没有反射(尚未).您需要探索其他选项,例如第三方库.

  • 你*可以*用TMP做到这一点.看看[magic_get](https://github.com/apolukhin/magic_get)和[结构化绑定](http://en.cppreference.com/w/cpp/language/structured_binding). (3认同)