Disallow negative argument for unsigned value with boost :: program_options

Suppose I have a program that uses boost :: program_options to parse command line arguments, and each has a value unsigned:

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

namespace po = boost::program_options;

int main(int argc, char* argv[]) {
    unsigned num;
    po::options_description desc;
    desc.add_options()
        ("num,n", po::value<unsigned>(&num), "Non-negative number");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    std::cout << "Number: " << num << '\n';
    return 0;
}

Then, if I pass a negative value on the command line, it takes it and wraps it around:

$ ./bponeg -n -1
Number: 4294967295

I would prefer that negative numbers cause an error (i.e. throw invalid_option_value) in the same way as if I wrote ./bponeg -n abc. From my own code, after parsing, it seems impossible to distinguish between the case when the user wrote -1or wrote 4294967295.

Can I instruct the program_options parser to reject negative inputs for values unsigned?

+4
1

, :

struct nonnegative {
    unsigned value;
};

void validate(boost::any& v, const std::vector<std::string>& values, nonnegative*, int)
{
    using namespace boost::program_options;
    validators::check_first_occurrence(v);

    std::string const& s = validators::get_single_string(values);
    if (s[0] == '-') {
        throw validation_error(validation_error::invalid_option_value);
    }

    v = lexical_cast<unsigned>(s);
}

nonnegative unsigned.

, int64_t , . .

+7

All Articles