我需要从boost::program_options::option_description
类获取默认值。
我检查了源代码,看起来它将默认值存储为std::string
和boost::any
,但它存储在私有m_default_as_text
中,因此我无法从中提取此信息那里。
我能得到的就是那样的格式化参数
arg(= 10)
但我只想获得10分。
我也可以通过调用boost::any
方法
value_semantic::apply_default
boost::any default_value;
opt_ptr->semantic()->apply_default(default_value)
但是当我在boost::any_cast
集合上进行迭代时,我不知道要做option_description
的确切类型,我只想打印它。
更新
namespace po = boost::program_options;
po::options_description descr("options");
descr.add_options()
("help,h", "produce help message")
("a", po::value<int>()->default_value(42));
for (auto opt: descr.options())
{
std::cout << opt->format_parameter() << std::endl;
}
这里打印
arg(= 42)
我希望在没有类型知识的情况下获得42作为字符串。
有什么办法吗?
答案 0 :(得分:0)
你可以使用(在调用商店之后):
if(vm["a"].defaulted())
{
//the value for a was set to the default value
std::string a_1 = vm["a"].as<std::string>();
//the other option is to get the int and lexical_cast it
std::string a_2 = boost::lexical_cast<std::string>(vm["a"].as<int>());
}
else
{
//vm["a"] was not defaulted
//So, why would you need to know the default value?
}
另一个选项(以及更好的方法)是使用boost :: lexical_cast将int转换为字符串(将值设置为参数而不是幻数强>):
constexpr int dv_a = 42;
//if (using C++11)
//const int dv_a = 42;
//if you are not using C++11
po::options_description descr("options");
descr.add_options()
("help,h", "produce help message")
("a", po::value<int>()->default_value(dv_a));
std::string string_dv_a = boost::lexical_cast<std::string>(dv_a);