我想将var发送给函数,如果它是一个类。我尝试使用std :: is_class,但这给了我一个错误,因为std :: is_class是运行时而不是预处理程序。我不能使预处理器工作。有什么建议么?在循环的功能“ toJson”中,我将类型添加到json对象。我需要检查类型是否为class,以便将class字段递归添加到json对象。
源代码:https://stackoverflow.com/a/34165367/13277578
template<typename Class, typename T>
struct PropertyImpl {
constexpr PropertyImpl(T Class::* aMember, const char* aName) : member{ aMember }, name{ aName } {}
using Type = T;
T Class::* member;
const char* name;
};
template<typename Class, typename T>
constexpr auto property(T Class::* member, const char* name) {
return PropertyImpl<Class, T>{member, name};
}
template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
(static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}
// the error in this function
template<typename T>
json toJson(const T& object)
{
json data;
// We first get the number of properties
constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;
// We iterate on the index sequence of size `nbProperties`
for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
// get the property
constexpr auto property = std::get<i>(T::properties);
using Type = typename decltype(property)::Type;
#if __is_class(Type) // C1017
// data[property.name] = toJson(object.*(property.member)) // recursive add the object fields
#else
// addFind(data, object.*(property.member), property.name)) // add the object field (WORK)
#endif
});
return data;
}
使用toJson的示例:
#define PROPERTY(CLASS, MEMBER) property(&CLASS::MEMBER, #MEMBER)
struct GetRooms
{
unsigned int status = 0;
RoomData roomData;
string name;
constexpr static auto properties = std::make_tuple(
PROPERTY(GetRooms, status),
PROPERTY(GetRooms, roomData),
PROPERTY(GetRooms, name)
);
};
GetRooms var;
json varAsJson = toJson(var);
if constexpr
正是我所需要的。它可以在编译时比较类型,这使我可以调用正确的函数,而完全忽略与该类型不兼容的其他函数。