gpt4 book ai didi

c++ - 为 std::vector boost 自定义验证器

转载 作者:行者123 更新时间:2023-11-30 05:14:18 25 4
gpt4 key购买 nike

我为 std::vector<double> 编写了以下自定义验证器.

typedef vector<double> coordinate;
void validate(boost::any& v,
const vector<string>& values,
coordinate*, int) {
std::cout << "Custom validator called\n";
coordinate c;
vector<double> dvalues;
for(vector<string>::const_iterator it = values.begin();
it != values.end();
++it) {
stringstream ss(*it);
copy(istream_iterator<double>(ss), istream_iterator<double>(),
back_inserter(dvalues));
if(!ss.eof()) {
std::cerr << "SS EOF\n";
throw po::invalid_option_value("Invalid coordinate specification sseof");
}
}
if(dvalues.size() != 2) {
std::cerr << "dvalues size\n";
throw po::invalid_option_value("Invalid coordinate specification dvalues size");
}
c.push_back(dvalues[0]);
c.push_back(dvalues[1]);
v = c;
}

然后我按以下方式添加选项:

coordinate c;
// Setup options.
po::options_description desc("Options");
desc.add_options()
("instruments.prop", po::value<coordinate>( &c )->multitoken(),
"plugin names" );

程序根本没有使用自定义验证器。我没有收到消息“已调用自定义验证程序”,如果使用我的验证程序,该消息应该已打印出来。相反,我收到此错误:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl

' what(): the argument ('1 2.9') for option 'instruments.name' is invalid Aborted (core dumped)

我的配置文件如下:

[乐器]
支撑= 1 2.9

关于如何从配置文件中解析多个参数而不像这样将它们写在单独的行中的任何想法:

[乐器]
Prop = 1
Prop = 2.9

最佳答案

改为编写自定义转换:

Live On Coliru

#include <boost/program_options.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <fstream>
#include <iostream>

namespace po = boost::program_options;
typedef std::vector<double> coordinate;

int main() {
coordinate c;

// Setup options.
po::options_description desc("Options");
desc.add_options()
("instruments.prop", po::value<std::string>()->multitoken()->notifier([&c](std::string const& v) {
auto it = boost::make_split_iterator(v, boost::token_finder(boost::algorithm::is_any_of(" ,")));
std::transform(it, {}, back_inserter(c), [](auto& s) {
return boost::lexical_cast<double>(s);
});
}),
"plugin names" );

std::ifstream ifs("input.txt");
po::variables_map vm;
store(po::parse_config_file(ifs, desc, false), vm);
po::notify(vm);

std::copy(c.begin(), c.end(), std::ostream_iterator<double>(std::cout << "c: ", " "));
std::cout << "\n";
}

打印

c: 1 2.9

关于c++ - 为 std::vector<double> boost 自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43512200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com