I'm using nlohmann::json to parse json string. I implement a util function GetValue
to retrieve object fields.
template<typename T1, typename T2>
bool CheckType(T1& it, T2& val) { return false; }
template<typename T1>
bool CheckType(T1& it, bool& val) { return it->is_boolean(); }
template<typename T1>
bool CheckType(T1& it, std::string& val) { return it->is_string(); }
....
template<typename T>
bool GetValue(nlohmann::json obj, std::string key, T& value, std::string &err) {
auto it = obj.find(key);
if (it != obj.end()) {
if (CheckType(it, val)) {
value = it->get<T>();
return true;
} else {
err = key + " type error";
}
} else {
err = key + " not found";
}
return false;
}
The function CheckType
looks ugly. What's the elegant way to do this?
Aucun commentaire:
Enregistrer un commentaire