我正在尝试使用自定义验证器而不是重载operator>>
来支持我的选项解析中的枚举类型。我做了以下事情:
#include <iostream>
#include <boost/program_options.hpp>
enum class MyEnum
{
OneThing,
AnotherThing
};
void validate(boost::any& v, const std::vector<std::string>& values,
MyEnum*, int)
{
// parse the enum from values[0]
std::cout << "Test" << std::endl;
MyEnum enumValue = MyEnum::OneThing;
v = enumValue;
}
int main(int argc, char*argv[])
{
namespace po = boost::program_options;
po::options_description desc("Options");
//desc.add_options()("myEnum", po::value<MyEnum>(), "MyEnum value"); // works fine
desc.add_options()("myEnum", po::value<MyEnum>()->default_value(MyEnum::OneThing), "MyEnum value"); // compiler error: Source type is not streamable
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
MyEnum myEnum = vm["myEnum"].as<MyEnum>();
return 0;
}
只要我不尝试设置default_value
,这样就可以正常工作,但是当我指定default_value时,我会得到error: static assertion failed: Source type is neither std::ostream able nor std::wostream able
。还有什么我需要(没有重载流操作符,这是我理解的使用验证器的全部要点)来允许自定义类型获得default_value?
答案 0 :(得分:3)
您可以设置默认值,但是,它需要知道如何在说明中表示默认值。
由于枚举不可流式化,因此自动方式不起作用,因此您必须指定它,例如:
default_value(MyEnum::OneThing, "OneThing")
<强> Live On Coliru 强>
#include <iostream>
#include <boost/program_options.hpp>
enum class MyEnum
{
OneThing,
AnotherThing
};
void validate(boost::any& v, const std::vector<std::string>& values,
MyEnum*, int)
{
// parse the enum from values[0]
std::cout << "Test" << std::endl;
MyEnum enumValue = MyEnum::OneThing;
v = enumValue;
}
int main(int argc, char*argv[])
{
namespace po = boost::program_options;
po::options_description desc("Options");
//desc.add_options()("myEnum", po::value<MyEnum>(), "MyEnum value"); // works fine
desc.add_options()("myEnum", po::value<MyEnum>()->default_value(MyEnum::OneThing, "OneThing"), "MyEnum value");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
MyEnum myEnum = vm["myEnum"].as<MyEnum>();
std::cout << std::boolalpha << (myEnum == MyEnum::OneThing) << "\n";
}
打印
true