Boost如何能够实现这样的语法?

use*_*312 3 c++ boost

http://www.boost.org/doc/libs/1_58_0/doc/html/program_options/tutorial.html

// Declare the supported options.
.............................................
desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
;
Run Code Online (Sandbox Code Playgroud)

是通过运算符重载?

如果是,那么哪个运营商超负荷?

你能使用一个简单的非Boost示例程序来模仿这种语法吗?

Chr*_*ger 6

desc.add_options()返回一个重载的对象operator().这意味着可以像调用该函数一样调用该对象.

更具体地说,options_descriptions::add_options()返回一个options_description_easy_init对象.这个对象有一个operator(),它返回一个引用*this:对任何operator()一个引用返回options_description_easy_init对象本身的引用,所以可以再次调用它.

你可以找到两者的源代码options_descriptions,并options_description_easy_init 在这里.

要自己复制,你可以这样做:

#include <iostream>

class callable {
public:
    class callable &operator()(const std::string &s) {
        std::cout << s << std::endl;
        return *this;
    }
};

callable make_printer() {
    return callable();
}

int main() {
    make_printer()("Hello, World!")("Also prints a second line");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)