Abr*_*ile 5 c++ boost-program-options
我正在使用boost程序选项从命令行参数获取布尔值.我希望我的论点被指定为"Y",是","N","否".
实际上我的代码使用临时字符串来完成它
boost program options最重要的是,我还使用另一个临时字符串获取默认值.
我做了所有这些工作,因为我尝试了下面的代码,但是没有用
namespace pod = boost::program_options;
("Section.Flag",
pod::value<bool>(&myFlag_bool)->default_value( false ),
"description")
Run Code Online (Sandbox Code Playgroud)
你知道升级程序选项是否可以比我用来实现它的更好?
您将以一种或另一种方式解析字符串。有几个选项,主要取决于您查询该值的频率。这是一个与我最近使用的类似的示例;CopyConstructable 和Assignable 因此它可以很好地与STL 配合使用。我想我需要做一些额外的事情才能让它与program_options一起工作,但你明白了要点:
#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_;
};
Run Code Online (Sandbox Code Playgroud)