23

我正在尝试验证对我定义的枚举的命令行输入,但得到编译器错误。我以使用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

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

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

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

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

1 回答 1

32

在您的情况下,您只需要重载即可从operator>>a 中提取 a ,如下所示: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;
}

不需要自定义验证器。

于 2011-03-06T18:43:59.010 回答