为Enum提升自定义验证器

时间:2011-03-06 17:09:29

标签: c++ boost validation boost-program-options

我正在尝试验证我已定义的Enum的命令行输入,但是会出现编译器错误。我以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. 我的场景和示例之间的区别是什么,除了我的是Enum,其他的是Structs? 编辑:我的方案不需要自定义验证程序重载。
  2. 有没有办法为Enum重载验证方法? 编辑:不需要。

1 个答案:

答案 0 :(得分:28)

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

#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;
}

不需要自定义验证器。