首页 > 解决方案 > 如何根据模板类型参数调用不同的函数?

问题描述

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()看起来很难看。这样做的优雅方法是什么?

标签: c++c++11templates

解决方案


不确定但是,如果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()功能。


推荐阅读