【问题标题】:Which C++ language feature is repeating parentheses after function call? [duplicate]哪个 C++ 语言功能在函数调用后重复括号? [复制]
【发布时间】:2016-12-07 20:18:55
【问题描述】:

我正在使用 boost::program_options 库,下面的代码用于创建选项描述并向其中添加选项:

po::options_description opts("SendFile Options");

    opts.add_options()("help,h", "Print this help message")
        ("other,o","This is the other");

我的问题是,哪个 C++ 语言功能允许您在调用 add_options 函数后以括号中包含的重复值的形式直接添加单独的描述?这叫什么,我将如何创建一个以这种方式工作的函数?

【问题讨论】:

  • 只需要编写一个返回可调用对象的函数。
  • 你可以重载operator()
  • 您说的完全正确,没有出现在类似的线程中。仍然是一个有点令人困惑的实现。

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


【解决方案1】:

简化示例:

#include <string>
#include <vector>
#include <iostream>

class Options {
public:
    Options& operator()(std::string text)
    {
        strings.push_back(text);
        return *this;

    }
    std::vector<std::string> strings;

};

int main()
{
    Options options{};
    options("Some text")
        ("more text")
        ("even more text");
    for(const auto& text : options.strings)
        std::cout << text << '\n';
}

生产:

Some text
more text
even more text

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 1970-01-01
    • 2016-10-13
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多