如何在C++中使用带有预处理器的 gcc __is_class
How to use gcc __is_class with preprocessor if in C++
如果函数是一个类,我想向函数发送一个变量。我尝试使用 std::is_class但这给了我一个错误,因为 std::is_class 是运行时而不是预处理器。如果工作,我无法制作预处理器。有什么建议吗?在循环中的函数"toJson"中,我将类型添加到 json 对象中。我需要检查类型是否为类,以便递归地将类字段添加到 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
正是我所需要的。它可以在编译时比较类型,这允许我调用正确的函数并完全忽略与此类型不兼容的其他函数。
if constexpr (std::is_class<Type>::value)
{
// call the class function
}
else
{
// not call the class function
}
相关文章:
- 错误:无效的预处理指令 #i 的意思是 #if?
- C++预处理会生成变量成员、资源库和映射
- 使用预处理指令检查是否包含标头?
- 预处理的 C/C++ 文件是否特定于计算机?
- 使用 GCC 对 C 文件进行部分预处理(不删除 "define" 指令)
- 在 CPLEX 中求解线性规划,无需剪切和预处理
- CPP -D 选项,用于预处理 Fortran 代码
- 错误:粘贴"tmp_UINT"和"+"未提供有效的预处理令牌
- 任务计划程序库的预处理不起作用 - 多定义错误
- Eclipse 问题 - 编译期间不考虑 .c 和 .cpp 文件中定义的预处理
- 使用python预处理后,C++(opencv)中的垫子类型数据与image_to_array相同
- Howo 使用 cl 预处理为 masm 组装生成一个单独的文件
- 我有一个预处理的 C/C++ 源文件 (cacti.i).如何从这个 .i 文件生成可执行二进制文件,以便我可以像 ./
- 如何使用Visual Studio C/C++编译器(cl.exe)来预处理我的objective-C代码
- 是具有预处理前分支实现的结构违反ODR
- 与不完整的Cholesky预处理的共轭梯度返回特征库的意外错误
- Visual Studio C - 无法输出预处理文件
- 在海湾合作委员会中加快宏观预处理的任何方法
- 所有结构成员的预处理器批处理
- 当头文件被预处理时是否有一个预处理器选项显示?