为什么 boost::program_options::bool_switch 的行为不像我预期的那样?

Why boost::program_options::bool_switch is not behaving like I expect?

下面的代码使用 po::bool_switch(&flag) 希望自动将正确的值分配给 flag

我的编译命令是clang++ -std=c++11 test.cpp -o test -lboost_program_options

所以我 运行 带有 ./test -h 的程序没有显示任何帮助消息。

为什么会这样?

#include <iostream>
#include <boost/program_options.hpp>

namespace
{
  namespace po = boost::program_options;
}

int main(int ac, char ** av)
{
  bool flag;

  po::options_description help("Help options");

  help.add_options()
    ( "help,h"
    , po::bool_switch(&flag)->default_value(false)
    , "produce this help message" );

  po::variables_map vm;

  po::parsed_options parsed
    = po::parse_command_line(ac,av,help);

  po::store(po::parse_command_line(ac,av,help),vm);

  if (flag)
  {
    std::cout << help;
  }
  po::notify(vm);

  return 0;
}

您应该在解析和存储参数后调用 notifystore只是填充了variables_map的内部数据结构。 notify 发布它们。

您的示例与 tutorial 中“入门部分”中的示例几乎完全相同。

并且 here 他们给出了一个非常大胆的警告,不要忘记它:

Finally the call to the notify function runs the user-specified notify functions and stores the values into regular variables, if needed.

Warning: Don't forget to call the notify function after you've stored all parsed values.

这应该有效:

po::variables_map vm;
po::parsed_options parsed
  = po::parse_command_line(ac,av,help);
po::store(po::parse_command_line(ac,av,help),vm);
po::notify(vm); // call after last store, and before accesing parsed variables

if (flag)
{
  std::cout << help;
}