gpt4 book ai didi

c++ - boost 枚举的自定义验证器

转载 作者:IT老高 更新时间:2023-10-28 21:51:21 25 4
gpt4 key购买 nike

我正在尝试验证我已定义的枚举的命令行输入,但出现编译器错误。我用过Handle complex options with Boost's program_options作为一个工作的例子。

namespace po = boost::program_options;

namespace Length
{

enum UnitType
{
METER,
INCH
};

}

void validate(boost::any& v, const std::vector<std::string>& values, Length::UnitType*, int)
{
Length::UnitType unit;

if (values.size() < 1)
{
throw boost::program_options::validation_error("A unit must be specified");
}

// make sure no previous assignment was made
//po::validators::check_first_occurence(v); // tried this but compiler said it couldn't find it
std::string input = values.at(0);
//const std::string& input = po::validators::get_single_string(values); // tried this but compiler said it couldn't find it

// I'm just trying one for now
if (input.compare("inch") == 0)
{
unit = Length::INCH;
}

v = boost::any(unit);
}

// int main(int argc, char *argv[]) not included

为了节省不必要的代码,我添加了如下选项:

po::options_description config("Configuration");
config.add_options()
("to-unit", po::value<std::vector<Length::UnitType> >(), "The unit(s) of length to convert to")
;

如果需要编译器错误,我可以发布它,但希望让问题看起来简单。我已经尝试寻找示例,但我真正能找到的唯一其他示例是 examples/regex.cpp from the Boost website .

  1. 我的场景和找到的例子有什么区别,除了我的是一个枚举,其他的是结构? 编辑:我的场景不需要自定义验证器重载。
  2. 有没有办法为枚举重载 validate 方法? 编辑:不需要。

最佳答案

在您的情况下,您只需重载 operator>> 即可从 istream 中提取 Length::Unit,如下所示:

#include <iostream>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>

namespace Length
{

enum Unit {METER, INCH};

std::istream& operator>>(std::istream& in, Length::Unit& unit)
{
std::string token;
in >> token;
if (token == "inch")
unit = Length::INCH;
else if (token == "meter")
unit = Length::METER;
else
in.setstate(std::ios_base::failbit);
return in;
}

};

typedef std::vector<Length::Unit> UnitList;

int main(int argc, char* argv[])
{
UnitList units;

namespace po = boost::program_options;
po::options_description options("Program options");
options.add_options()
("to-unit",
po::value<UnitList>(&units)->multitoken(),
"The unit(s) of length to convert to")
;

po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
po::notify(vm);

BOOST_FOREACH(Length::Unit unit, units)
{
std::cout << unit << " ";
}
std::cout << "\n";

return 0;
}

不需要自定义验证器。

关于c++ - boost 枚举的自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com