带有json文件的C ++ Boost程序选项 [英] C++ Boost program options with json file
本文介绍了带有json文件的C ++ Boost程序选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以使用增强程序选项库: http: //www.boost.org/doc/libs/1_64_0/doc/html/program_options.html
It is possible with boost program options library: http://www.boost.org/doc/libs/1_64_0/doc/html/program_options.html
在这里读取json格式的文件作为输入文件?
to read json formatted file as an input file here?
或者如果我在json之类的文件中有一些配置,我需要自己解析,例如:
Or if I have some config in json like file, I need to parse it myself, with for example: http://www.boost.org/doc/libs/1_64_0/doc/html/property_tree.html
推荐答案
我遇到了同样的问题.这是我基于property_tree的program_options库的JSON解析器的实现:
I've met the same problem. Here is my implementation of JSON parser for program_options library, based on property_tree:
template <class charT> void parseChildren(std::string prefix, boost::property_tree::ptree& tree, boost::program_options::parsed_options& options)
{
if (tree.size() == 0)
{
//cut first dot
std::basic_string<charT> name = prefix.substr(1);
std::basic_string<charT> value = tree.data();
boost::program_options::basic_option<charT> opt;
opt.string_key = name;
opt.value.push_back(value);
opt.unregistered = (options.description->find_nothrow(name, false) == nullptr);
opt.position_key = -1;
options.options.push_back(opt);
}
else
{
for (auto it = tree.begin(); it != tree.end(); ++it)
{
parseChildren<charT>(prefix + "." + it->first, it->second, options);
}
}
}
template <class charT>
void parseJsonOptions(std::basic_istream<charT>& is, boost::program_options::parsed_options& options)
{
boost::property_tree::basic_ptree<std::basic_string<charT>, std::basic_string<charT>> pt;
boost::property_tree::read_json(is, pt);
parseChildren<charT>(std::basic_string<charT>(), pt, options);
}
template <class charT>
boost::program_options::basic_parsed_options<charT> parse_json_config_file(std::basic_istream<charT>& is, const boost::program_options::options_description& desc, bool allow_unregistered = false)
{
// do any option check here
boost::program_options::parsed_options result(&desc);
parseJsonOptions(is, result);
return boost::program_options::basic_parsed_options<charT>(result);
}
使用方式如下:
po::variables_map vm;
std::ifstream configFileStream(configFilePath_.generic_string());
store(parse_json_config_file(configFileStream, algorithmsDesc_), vm);
notify(vm);
这篇关于带有json文件的C ++ Boost程序选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文