获取类中的字段数

问题描述 投票:5回答:2

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

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);

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

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

c++ c++11 templates template-meta-programming typetraits
2个回答
5
投票

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

C++14 Reflections Without Macros, Markup nor External Tooling / 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>{});
}

这会让你获得实地数量。当然,你还需要巧妙构思的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

这应该足够了。


7
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.