Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boolean options from boost program options

I am using boost program options to get boolean values from command line argument. I would like my argument to be specified as "Y", Yes", "N", "No".

Actually my code did it using a temporary string that

  1. will be parsed by boost program options
  2. checked against "Y", "Yes", "N" or "No"
  3. assigned to the boolean variable member.

On top of that I am also using another temp string getting the default value.

I did all that work since I tried thee code below that didn't work

      namespace pod = boost::program_options;

      ("Section.Flag", 
           pod::value<bool>(&myFlag_bool)->default_value( false ), 
           "description")

Do you know whether boost program options can be used some better then the one I use to achieve that?

like image 593
Abruzzo Forte e Gentile Avatar asked Oct 11 '22 15:10

Abruzzo Forte e Gentile


1 Answers

You are going to be parsing a string one way or another. There are a couple options, mostly depending on how often you are going to be querying this value. Here is an example of something similar to what I recently used; CopyConstructable and Assignable so it works well with STL. I think I needed to do a few extra things to get it to work with program_options, but you get the gist:

#include <boost/algorithm/string.hpp>

class BooleanVar
{
public:
    BooleanVar(const string& str)
        : value_(BooleanVar::FromString(str))
    {
    };

    BooleanVar(bool value)
        : value_(value)
    {
    };

    BooleanVar(const BooleanVar& booleanVar)
        : value_(booleanVar)
    {
    };

    operator bool()
    {
        return value_;
    };

    static bool FromString(const string& str)
    {
        if (str.empty()) {
            return false;
        }

        // obviously you could use stricmp or strcasecmp(POSIX) etc if you do not use boost
        // or even a heavier solution using iostreams and std::boolalpha etc
        if (
            str == "1" 
            || boost::iequals(str, "y")
            || boost::iequals(str, "yes")
            || boost::iequals(str, "true")
        )
        {
            return true;
        }

        return false;
    };

protected:
    bool value_;
};
like image 155
adzm Avatar answered Oct 18 '22 01:10

adzm