[英]Boost.Program_Options: Why does options_description_easy_init::operator() not have an overload for std::string?
Consider this MCVE:考虑这个 MCVE:
#include <boost/program_options.hpp>
#include <iostream>
#include <map>
namespace po = boost::program_options;
using namespace std;
po::options_description createOptions(const std::string& description, const map<string, string>& opts) {
po::options_description newoptions(description);
for (const auto& [k, v] : opts) {
newoptions.add_options()(k, v);
}
return newoptions;
}
int main() {
map<string, string> descMap = {
{ "key", "description" },
{ "hello", "world" }
};
auto opts = createOptions("My options", descMap);
cout << opts << endl;
}
I am trying to write a convenience function to reduce the amount of C&P code when inserting similar options into an options_description
object (the original code uses notifiers which were removed for simplicity, but add even more boilerplate).我正在尝试编写一个方便的函数,以在将类似选项插入
options_description
对象时减少 C&P 代码的数量(原始代码使用通知程序,为了简单起见,这些通知程序已被删除,但添加了更多样板文件)。 To my surprise, there is no options_description_easy_init::operator()
overload that accepts std::string
, thus the example fails to compile .令我惊讶的是,没有接受
std::string
options_description_easy_init::operator()
重载,因此该示例无法 compile 。
While I could easily make the example work by calling .c_str()
on k
and v
within the for loop, of course this would be dangerous .虽然我可以通过在 for 循环中对
k
和v
调用.c_str()
来轻松地使示例工作, .c_str()
当然会很危险。 Is there any reason why the boost devs left out such an important overload?有什么理由让 boost 开发人员遗漏了如此重要的过载? Why didn't they use
const std::string&
as argument in the first place?为什么他们不首先使用
const std::string&
作为参数?
And how can I make this code work without .c_str()
?以及如何在没有
.c_str()
情况下使此代码工作? There is no indication that the pointer memory will be copied internally (which would be odd anyway) and I really don't feel like going back in time and managing memory on my own :-)没有迹象表明指针内存将在内部复制(无论如何这很奇怪),我真的不想回到过去并自己管理内存:-)
Looking into the implementation , it seems that internally the const char*
argument passed to options_description_easy_init::operator()
is wrapped by a new option_description
object , which eventually converts the argument into a std::string
.查看实现,似乎在内部传递给
options_description_easy_init::operator()
的const char*
参数由一个新的option_description
对象包装,该对象最终将参数转换为std::string
。 So as commented by @pptaszni, it is safe to call .c_str()
on the std::string
arguments to pass them to the program options.因此,作为由@pptaszni评论说,这是安全地调用
.c_str()
上std::string
参数将它们传递给程序选项。
What I still don't understand, however, is why there is not an std::string
overload.然而,我仍然不明白的是为什么没有
std::string
重载。 I consider this a design flaw (also considering that options_description
has a constructor taking std::string
).我认为这是一个设计缺陷(也考虑到
options_description
有一个采用std::string
的构造函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.