gpt4 book ai didi

c++ - 指向成员 : works in GCC but not in VS2015 的指针

转载 作者:IT老高 更新时间:2023-10-28 22:39:43 25 4
gpt4 key购买 nike

我正在尝试实现一个“属性”系统来将 C++ 实例转换为 JSON,反之亦然。我从 Guillaume Racicot 在这个问题 (C++ JSON Serialization) 中的回答中提取了部分代码并对其进行了简化。

这是我的操作方式。我有一个 Property 类:

template <typename Class, typename T>
struct Property {
constexpr Property(T Class::* member, const char* name) : m_member(member), m_name(name) {}

T Class::* m_member;
const char* m_name;
};

m_member 指向 Class

的特定成员

假设我想为 User 类定义属性,我希望能够像这样继续,以便能够为成员分配属性名称:

class User
{
public:
int age;

constexpr static auto properties = std::make_tuple(
Property<User, int>(&User::age, "age")
);
}

此代码在 GCC(http://coliru.stacked-crooked.com/a/276ac099068579fd) 中编译并正常工作,但在 Visual Studio 2015 Update 3 中不正确。我收到这些错误:

main.cpp(19) : error C2327 : 'User::age' : is not a type name, static, or enumerator
main.cpp(19) : error C2065 : 'age' : undeclared identifier
main.cpp(20) : error C2672 : 'std::make_tuple' : no matching overloaded function found
main.cpp(20) : error C2119 : 'properties' : the type for 'auto' cannot be deduced from an empty initializer

是否有解决方法使其在 Visual Studio 2015 Update 3 中工作?

最佳答案

我首选的解决方法是将 properties 成员数据替换为 properties 成员函数:

class User
{
public:
int age;

constexpr static auto properties() { return std::make_tuple(
Property<User, int>(&User::age, "age")
); }
};

这是因为在定义成员函数时,类被认为是完全定义的。它还具有如果使用odr,则不需要单独定义properties的理想属性。

关于c++ - 指向成员 : works in GCC but not in VS2015 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com