【发布时间】:2017-08-22 15:08:53
【问题描述】:
我正在使用 boost program_options,但找不到指定异常消息以包含用户输入的值的方法,例如:
error: the argument for option '--ipc' is invalid: "shm"
我将用户输入的值传递给下面的调用,但这没有任何效果:
throw po::validation_error(po::validation_error::invalid_option_value, enteredValue);
错误信息仍然是这个:
error: the argument for option '--ipc' is invalid
这是我的完整代码:
#include <iostream>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
namespace po_style = boost::program_options::command_line_style;
namespace po = boost::program_options;
enum class Ipc : int8_t
{
TCP = 0,
UDP,
};
// Convert a log severity level to its name formatted as a string
// Enum cannot contain methods but you can add external methods like this one
static const char* to_string(const Ipc& id)
{
switch (id)
{
case Ipc::TCP: return "TCP";
case Ipc::UDP: return "UDP";
default: return "TCP";
}
}
// This function is called for arguments of the type Ipc
void validate(boost::any& v, const vector<string>& values, Ipc*, int)
{
po::validators::check_first_occurrence(v);
const string& enteredValue = po::validators::get_single_string(values);
const string& enteredValueUpper = boost::to_upper_copy(enteredValue);
if (enteredValueUpper == "TCP")
{
v = boost::any(Ipc::TCP);
}
else if (enteredValueUpper == "UPD")
{
v = boost::any(Ipc::UDP);
}
else
{
throw po::validation_error(po::validation_error::invalid_option_value, enteredValue);
}
}
int main(int argc, char* argv[])
{
try
{
// Declare all allowed options using the options_description class.
po::options_description desc("Usage");
desc.add_options()
("help,h", "produce help message")
("ipc,i", po::value<Ipc>()->default_value(Ipc::TCP, "TCP"), "set the inter-process communication");
po::variables_map cmdline;
po::store(po::command_line_parser(argc, argv)
.options(desc)
.style(po_style::unix_style | po_style::case_insensitive)
.run(), cmdline);
po::notify(cmdline);
// -i[--ipc] set the inter-process communication
if (cmdline.count("ipc"))
{
Ipc level = cmdline["ipc"].as<Ipc>();
cout << "ipc=" << to_string(level) << endl;
}
// -h[--help] produce help message
if (cmdline.count("help"))
{
cout << desc << "\n";
return 0;
}
}
catch (exception& e)
{
cerr << "error: " << e.what() << "\n";
return 1;
}
catch (...)
{
cerr << "Exception of unknown type!\n";
}
return 0;
}
【问题讨论】:
-
这是哪个版本的 Boost?它确实seem a bit odd..
-
我正在使用 boost 1.64.0(这是我第一个使用 boost 的程序)。到底什么是奇怪的?
-
奇怪的是该类型消息的格式字符串是
"the argument ('%value%') for option '%canonical_option%' is invalid"。%包围的标记是由适当的参数替换的。乍一看,即使是空值,我也希望('')位保持不变。我得仔细研究一下格式化代码,看看那里发生了什么。 -
如果有帮助,我正在使用 Visual Studio 2015,问题包括构建的完整代码示例。
-
原来答案很简单,使用派生异常类:
throw po::invalid_option_value(enteredValue);
标签: c++ boost boost-program-options