为Enum提升自定义验证器

E-r*_*ich 21 c++ validation boost boost-program-options

我试图验证命令行输入到我已定义的枚举,但得到编译器错误.我使用Handle复杂选项和Boost的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
Run Code Online (Sandbox Code Playgroud)

为了备用包含更多代码而不是必要的代码,我将添加如下选项:

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

如果需要编译器错误,我可以发布它,但希望保持问题简单.我试过寻找示例,但我能找到的唯一其他示例是Boost网站上examples/regex.cpp.

  1. 我的场景和找到的示例之间有什么区别,除了我的是Enum,其他的是Structs?编辑:我的方案不需要自定义验证器重载.
  2. 有没有办法重载Enum 的验证方法?编辑:不需要.

Emi*_*ier 31

在你的情况,你只需要重载operator>>提取Length::Unitistream,如下所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

不需要自定义验证器.


归档时间:

查看次数:

7090 次

最近记录:

7 年,4 月 前