0

如标题所述:

struct AXmlConfigurator : private boost::noncopyable {
protected:
    std::string configuration_file_;
    std::map<std::string, std::string> parameters_;
    ptree ptree_;

public:

    AXmlConfigurator(const std::string &argConfigurationFile) :
        configuration_file_(argConfigurationFile) {
        read_xml(configuration_file_, ptree_);
    }

    ~AXmlConfigurator() {}

    template<typename Type> inline
    Type get(const std::string & argPath, Type argDefault) const {
        Type value = ptree_.get<Type>(argPath, argDefault);
        parameters_.insert(std::pair<std::string,std::string>(argPath, value));
        return value;
    }

    template<class Type , class Translator> inline
    typename boost::enable_if<detail::is_translator<Translator>, Type>::type
    get(const std::string &argPath, const Type &argDefault, Translator tr) const {
        Type value = ptree_.get(argPath, argDefault);
        parameters_.insert(std::pair<std::string,std::string>(argPath, value));
        return value;
    }
    void logConfiguration() {
        for(std::map<std::string, std::string>::const_iterator it = parameters_.begin() ; it != parameters_.end() ; ++it) {
            std::cout << (*it).first << " => " << (*it).second << std::endl;
        }
    }

};

我想包装 boost::property_tree::ptree 以将参数/值作为字符串存储到映射中,然后通过 logConfiguration 显示它们。

问题是地图的插入不接受值作为字符串,因为值类型未指定......

我没有想法,所以任何帮助表示赞赏!

4

2 回答 2

0

由于您需要数据为 a std::string,因此请更改:

    Type value = ptree_.get<Type>(argPath, argDefault);

至:

    std::string value = ptree_.get<std::string>(argPath, argDefault);
//  ^^^^^^^^^^^                    ^^^^^^^^^^^
于 2013-04-12T18:45:02.710 回答
0

好吧,这就是我最终所做的,它非常令人兴奋,但我并不追求这件事的表现,所以它会完成这项工作:

template<typename Type>
Type get(const std::string & argPath, Type argDefault) {
    std::string value = "a";
    try {
        value = ptree_.get<std::string>(argPath);
    } catch(ptree_bad_path &e) {
        return argDefault;
    }

    parameters_.insert(std::pair<std::string, std::string>(argPath,value));
    return ptree_.get<Type>(argPath, argDefault);
}

template<class Type , class Translator>
typename boost::enable_if<detail::is_translator<Translator>, Type>::type
get(const std::string &argPath, const Type &argDefault)  {
    std::string value = "";
    try {
        value = ptree_.get<std::string>(argPath);
    } catch(ptree_bad_path &e) {
        return argDefault;
    }

    parameters_.insert(std::pair<std::string,std::string>(argPath, value));
    return ptree_.get(argPath, argDefault);
}

我只是按照 Drew 的建议将参数作为字符串检索,只是在需要时捕获异常并返回默认值...

于 2013-04-12T21:16:16.007 回答