使用Boost::program_options允许多次出现自定义类型
allow multiple occurrences of custom type using Boost::program_options
是否有任何方法可以允许在boost::program_options
中多次出现自定义类型(struct
) ?我发现各种来源指定这可以使用std::vector
完成,但我想实现相同的使用自定义数据类型。然而,这个结构体确实包含一个std::vector
,我想在那里存储数据。
代码示例真的很有帮助。
但是,既然结构体将包含vector,为什么不绑定该vector呢?简单示例:
Live On Coliru
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/cmdline.hpp>
#include <iostream>
#include <vector>
struct my_custom_type {
std::vector<std::string> values;
friend std::ostream& operator<<(std::ostream& os, my_custom_type const& mct) {
std::copy(mct.values.begin(), mct.values.end(), std::ostream_iterator<std::string>(os << "{ ", ", "));
return os << "}";
};
};
int main(int argc, char** argv) {
namespace po = boost::program_options;
my_custom_type parse_into;
po::options_description desc;
desc.add_options()
("item", po::value<std::vector<std::string> >(&parse_into.values), "One or more items to be parsed")
;
try {
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc, po::command_line_style::default_style), vm);
vm.notify();
std::cout << "Parsed custom struct: " << parse_into << "n";
} catch(std::exception const& e) {
std::cerr << "Error: " << e.what() << "n";
}
}
当有26个参数调用时,如./test --item={a..z}
,它打印:
Parsed custom struct: { a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, }
如果您想以"特殊"的方式"自动"处理转换,您可以查看
- 自定义验证器(http://www.boost.org/doc/libs/1_59_0/doc/html/program_options/howto.html#idp343336928)
- 自定义通知器(一个简单的例子见例63.1)。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 为什么这个自定义分配器的析构函数在 GCC/MSVS 的 stdlib 中被调用两次
- 处理许多自定义异常的最佳方法是什么
- CMAKE自定义目标仅运行一次
- 自定义char*插入功能多次运行时会产生运行时错误
- 不允许对自定义类型进行多次隐式转换?
- 如果构建和破坏了许多向量,自定义分配器会提高性能<T>吗?
- 第二次推送时,优先级队列出现自定义比较器分段故障
- QListWidget性能与许多自定义项目
- 使用Boost::program_options允许多次出现自定义类型
- sort——给定一个自定义排序函数,在一次比较中可以进行多个排序查询
- 自定义分配器- Microsoft std::map实现对相同的元素进行两次重新分配,GCC工作得很好
- 自定义库在应用程序中,我必须包括库依赖头两次