【问题标题】:Boost.Program_Options: Why does options_description_easy_init::operator() not have an overload for std::string?Boost.Program_Options:为什么 options_description_easy_init::operator() 没有 std::string 的重载?
【发布时间】:2020-05-03 12:30:23
【问题描述】:

考虑一下这个 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;
}

我正在尝试编写一个便利函数,以在将类似选项插入options_description 对象时减少 C&P 代码的数量(原始代码使用通知程序,为简单起见已删除,但添加了更多样板文件)。 令我惊讶的是,there is no options_description_easy_init::operator() overload that accepts std::string,因此以 fails to compile 为例。

虽然我可以通过在 for 循环中对 kv 调用 .c_str() 来轻松地使示例工作,当然是 this would be dangerous。为什么 boost 开发者遗漏了如此重要的过载?他们为什么不首先使用const std::string&amp; 作为参数?

如果没有.c_str(),我怎样才能使这段代码工作?没有迹象表明指针内存将在内部复制(无论如何这会很奇怪),我真的不想回到过去并自己管理内存:-)

【问题讨论】:

  • 您可以拨打c_str()使其工作,不会有危险。参数为const char*,这意味着使用此参数调用的函数不拥有指向的内存,因此必须在函数返回后将其复制以进行进一步处理。如果参数为const std::string&amp;,则会调用相同类型的副本

标签: c++ boost c++17 boost-program-options c-str


【解决方案1】:

查看implementation,似乎在内部传递给options_description_easy_init::operator()const char* 参数被new option_description object 包装,最终converts the argument into a std::string。因此,正如 @pptaszni 所评论的,std::string 参数上调用 .c_str() 以将它们传递给程序选项是安全的。

然而,我仍然不明白为什么没有std::string 重载。我认为这是一个设计缺陷(还考虑到options_description 有一个constructor taking std::string)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多