Search code examples
boost-program-options

Boost Program Options optional argument precedence


The application has two options: a and file. file is a positional option. Both a and file have an argument of type string, which can be omitted. (I have set an implicit empty string for both).

The desired behaviour is as follows:

  1. $ program -> file: ""

  2. $ program file.txt -> file: "file.txt"

  3. $ program --a -> a: "", file: ""

  4. $ program --a file.txt -> a: "", file: "file.txt"

  5. $ program --a x file.txt -> a: "x", file: "file.txt"

However, option 4 is intepreted as a: "file.txt", file: "". Is there any way to inform program_options about how to resolve this ambiguous situation? ($ program --a -- file.txt does work as expected, but I would like to have this working without the extra -- as well.) I am using the empty string to indicate 'not specified' currently, but this is not a requirement.


Solution

  • I solved the problem by manually moving the argument from a to file if a was specified like this:

    // Fix argument precedence
    if (!vm.count("file") && vm.count("a"))
    {
        vm.insert(std::make_pair("file", vm.at("a")));
        vm.at("a").as<std::string>() = std::string();
    }