views:

746

answers:

3

When using boost::program_options, how do I set the name of an argument for boost::program_options::value<>()?

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

int main()
{
  boost::program_options::options_description desc;

  desc.add_options()
    ("width", boost::program_options::value<int>(),
     "Give width");

  std::cout << desc << std::endl;

  return 0;
}

The above code gives:

  --width arg           Give width

What I want is to replace the arg name with something more descriptive like NUM:

  --width NUM           Give width
A: 

One can replace arg with something different via the global variable boost::program_options::arg:

boost::program_options::arg = "NUM";

But as that is a global variable, it doesn't help much to fix the problem when multiple option might require different arguments.

Grumbel
+5  A: 

The program_options::value_semantic class doesn't parameterize the argument name, so I think you will have to define your own class. Something like this:

struct my_arg_type
    : public boost::program_options::typed_value<int>
{
    my_arg_type(std::string const& name)
        : boost::program_options::typed_value<int>(&my_value)
        , my_name(name)
        , my_value(0)
    {
    }
    std::string name() const { return my_name; }
    std::string my_name;
    int my_value;
};

boost::program_options::options_description desc;

my_arg_type arg("foo");
desc.add_options()
    ("width", &arg, "give width");

This should give something like:

--witdh foo    give width
Tim Sylvester
A: 

The approach given by Codebender is the only one you can use. This is actually intentional -- using "NUM" for name of argument appears to be micro-optimization that is not worth doing. A good description of the option should also say what kind of argument is expected.

Vladimir Prus
Calling it "micro-optimization" is kind of stupid, considering that pretty much every single command line application on earth does it. I have yet to see a single one that doesn't give its arguments proper types or names.
Grumbel
Do you think that "stupid" is the right terminology to use when discussing potential changes with a maintainer of a free library?
Vladimir Prus
I just get a little pissed when peolpe tell me that a feature that is used by virtual every single command line application outthere is "not worth doing" in boost::program_options.
Grumbel
Be nice, guys. It's not something I would consider the least bit important, but whether a change is worthwhile is the sole decision of the person doing the work (or the person paying them). Call it a learning experience; that is the whole point of this site, after all. (BTW, Vladimir, your comments really should not be an "answer," which I suspect is the source of the down-voting.)
Tim Sylvester