I\'m trying to implement a \"property\" system to convert C++ instances into JSON and vice versa. I took a part of the code from Guillaume Racicot\'s answer in this question (C+
MSVC doesn't know enough about User
when it wants to calculate the type of properties
to know it has a member age
.
We can work around the problem.
templatestruct tag_t{constexpr tag_t(){};};
templateconstexpr tag_t tag{};
template
using properties = decltype( get_properties( tag ) );
class User
{
public:
int age;
};
constexpr auto get_properties(tag_t) {
return std::make_tuple(
Property(&User::age, "age")
);
}
In the JSON reflection code, simply replace std::decay_t
with get_properties( tag
.
This has a few advantages. First you can retrofit some classes you do not own or wish to modify with properties seamlessly. With careful namespace use and ADL enabling the point of call, you can even do so for (some) types within std
(with oublic members only; pair at the least).
Second it avoids possible ODR-use requirements on properties. Properties is now a constexpr
return value not some global data that may require storage.
Third it permits properties to be written out-of-line with the class definition like above, or inline as a friend
within the class, for maximium flexibility.