Reputation: 14869
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
boost program options
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?
Upvotes: 5
Views: 3723
Reputation: 4136
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_;
};
Upvotes: 4