【发布时间】:2025-11-22 13:55:02
【问题描述】:
使用boost::program_options,我需要设置default_value 以使该默认值在帮助消息中可见。但是,仍然需要知道是否应用了默认值或是否提供了参数。 (在某些情况下,如果提供了参数,该逻辑将覆盖现有配置)。
可能的解决方案:
-
删除默认值:但是帮助消息不会显示默认值。
-
找到一种方法来检查是否提供了参数(如何?)
-
两次创建
option_description(一个有默认值,另一个没有)。不理想。int main( int argc, char* argv[]) { namespace po = boost::program_options; namespace fs = boost::filesystem; std::string ip; std::string port; const std::string ip_arg = "ip"; const std::string port_arg = "ip"; po::options_description options("Options"); options.add_options() (ip_arg, po::value<std::string>(&ip, "IP")->default_value("127.0.0.1") (port_arg, po::value<std::string>(&port, "Port")->default_value("80")) ; po::variables_map vm; try { using bs = po::command_line_style::style_t; boost::program_options::store( boost::program_options::command_line_parser(argc, argv) .options(options) .style(bs::long_allow_next | bs::allow_long | bs::allow_short | bs::allow_dash_for_short | bs::long_allow_adjacent | bs::short_allow_adjacent | bs::short_allow_next | bs::allow_long_disguise) .run(), vm); po::notify(vm); } catch( ...) { std::cerr << "Some error" << std::endl; return 1; } std::stringstream ss; ss << options; std::cout << ss.str() << std::endl; // Print help, visible defaults if (vm.count(port_arg)) { // Argument was provided, so make something } else { // Argument was no provided, make something else. } return 0; }
如何检测是否提供了参数,或者是否应用了默认值?
【问题讨论】:
标签: c++ boost boost-program-options