我正在使用 boost 程序选项从命令行参数中获取 bool 值。我希望我的论点被指定为“Y”、"is"、“N”、“否”。
实际上我的代码是使用一个临时字符串完成的
- 将被
boost程序选项解析
- 根据“Y”、“Yes”、“N”或“No”进行检查
- 分配给 bool 变量成员。
除此之外,我还使用了另一个获取默认值的临时字符串。
我做了所有这些工作,因为我尝试了下面不起作用的代码
namespace pod = boost::program_options;
("Section.Flag",
pod::value<bool>(&myFlag_bool)->default_value( false ),
"description")
你知道提升程序选项是否可以比我用来实现它的选项更好地使用吗?
最佳答案
您将以一种或另一种方式解析字符串。有几个选项,主要取决于您查询该值的频率。这是一个类似于我最近使用的例子; 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_;
};
关于c++ - 来自 boost 程序选项的 bool 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5103057/