I want to send a var to a function if is it a class. I try with std::is_class but this gave me an erros because std::is_class is run time and not a preprocessor. I can't make the preprocessor if to work. any suggestions? in the function 'toJson' in the loop I am adding the types to the json object. I need to check if the type is class, for recursive adding the classes fields to the json object.
source code: 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;
}
example of using 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);