c++ - 如何根据模板类型参数调用不同的函数?
问题描述
我nlohmann::json
用来解析 json 字符串。我实现了一个 util 函数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()
功能。
推荐阅读
- java - > 无法创建侦听器:格式化程序 {[com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask$Formatter@1326df32
- selenium - 使用 QAF 时如何在 TestNG XML 文件中配置一项测试以启动两个驱动程序,例如 Chrome 驱动程序和 Android 驱动程序
- amazon-web-services - 如何使用带有索引的 aws 胶水创建表?
- ruby - ruby-snmp:如何自动将响应转换为正确的类型?
- excel - 如何为列中的每个填充单元格循环特定代码
- amazon-web-services - 如何将事件发送到 AWS Lambda 函数的所有正在运行的实例
- javascript - JavaScript 本地文件夹访问
- firebase - Firebase Auth 在 TWA 中不起作用,但在 PWA 中起作用
- php - 查询 Laravel Eloquent 多对多,其中所有 id 都相等
- django - 使用“添加更多”功能到页面(模板)而不提交现有表单(和值)并最终提交