您可以使用编译时可用的元数据来完成此操作。但是,我们必须手动完成:
template<typename Class, typename T>
struct Property {
constexpr Property(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 makeProperty(T Class::*member, const char* name) {
return Property<Class, T>{member, name};
}
现在我们有一个类可以容纳我们期望的元数据。以下是如何使用它:
struct Dog {
constexpr static auto properties = std::make_tuple(
makeProperty(&Dog::barkType, "barkType"),
makeProperty(&Dog::color, "color")
);
private:
std::string barkType;
std::string color;
};
现在我们可以用递归做迭代就可以了:
template<std::size_t iteration, typename T, typename U>
void accessGetByString(T&& object, std::string name, U&& access) {
// get the property
constexpr auto property = std::get<iteration>(std::decay_t<T>::properties);
if (name == property.name) {
std::forward<U>(access)(std::forward<T>(object).*(property.member));
}
}
template<std::size_t iteration, typename T, typename U>
std::enable_if_t<(iteration > 0)>
getByStringIteration(T&& object, std::string name, U&& access) {
accessGetByString<iteration>(std::forward<T>(object), name, std::forward<U>(access));
// next iteration
getByStringIteration<iteration - 1>(std::forward<T>(object), name, std::forward<U>(access));
}
template<std::size_t iteration, typename T, typename U>
std::enable_if_t<(iteration == 0)>
getByStringIteration(T&& object, std::string name, U&& access) {
accessGetByString<iteration>(std::forward<T>(object), name, std::forward<U>(access));
}
template<typename T, typename U>
void getByString(T&& object, std::string name, U&& access) {
getByStringIteration<std::tuple_size<decltype(std::decay_t<T>::properties)>::value - 1>(
std::forward<T>(object),
name,
std::forward<U>(access)
);
}
最后,您可以使用这个工具,如:
struct MyAccess {
void operator()(int i) { cout << "got int " << i << endl; }
void operator()(double f) { cout << "got double " << f << endl; }
void operator()(std::string s) { cout << "got string " << s << endl; }
}
Dog myDog;
getByString(myDog, "color", MyAccess{});
这肯定可以通过重载lambda简化。要了解更多关于超载拉姆达,看到这个blog post
原始代码从答案被采取:C++ JSON Serialization
有做这样的事情更简单的建议。 这覆盖P0255r0
这回答不同的问题解释了它相当不错:http://stackoverflow.com/a/15550632/247763 – derekerdmann
顺便说一句,请不要使用' typedef struct T {}类型;'form。这不是古老的C'struct T {};''你就是需要做的。 –
很高兴知道 - 谢谢!这是我第一次在12年内再次使用C++ :) –