我试图理解boost库的program_options中的示例( http://www.boost.org/doc/libs/1_38_0/doc/html/program_options/tutorial.html#id3761458

特别是这部分:

desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
;

他到底在做什么,这是什么技术?

这部分desc.add_options()可能是函数调用但是other()如何适合这里?这是某种运算符重载吗?

谢谢!

有帮助吗?

解决方案

“add_options()”函数实际上返回一个仿函数,即一个覆盖()运算符的对象。这意味着以下函数调用

desc.add_options() ("help", "produce help message");

实际上扩展为

desc.add_options().operator()("help", "produce help message");

“operator()”还会返回一个仿函数,以便可以按照您所示的方式链接调用。

其他提示

推测add_options()会返回某种类型的仿函数,该函数有operator()重载以支持“链接”。 (这是一种非常有用的技术,BTW)

重载(...)允许您创建一个类似于函数的类。

例如:

struct func
{
    int operator()(int x)
    {
        cout << x*x << endl;
    }
};

...

func a;
a(5); //should print 25

但是如果你让operator()返回一个对象的引用,那么你可以“链接”运算符。

struct func
{
    func& operator()(int x)
    {
        cout << x*x << endl;
        return *this;
    }
};

...

func a;
a(5)(7)(8); //should print 25 49 64 on separate lines

由于a(5)返回a,(a(5))(7)与 a(5)或多或少相同;一个(7);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top