我正在使用 nlohmann::json
来解析 json 字符串。我实现了一个实用函数 GetValue()
来检索对象字段。
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;
}
CheckType()
函数看起来很难看。执行此操作的优雅方法是什么?
最佳答案
不确定,但是,如果 get()
支持在错误类型的情况下抛出,在我看来写一些东西更简单
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()) {
try {
value = it->get<T>();
return true;
}
catch (...) { // catching the correct exception; see library documentation
err = key + " type error";
}
} else
err = key + " not found";
return false;
}
完全避免使用 CheckType()
函数。
关于c++ - 如何根据模板类型参数调用不同的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56700343/