这种编程技术是什么? (提升图书馆)

时间:2009-05-01 01:08:17

标签: c++ boost

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

特别是这部分:

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

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

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

谢谢!

2 个答案:

答案 0 :(得分:14)

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

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

实际上扩展为

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

“operator()”也返回一个仿函数,这样就可以按照你所示的方式链接调用。

答案 1 :(得分:11)

大概add_options()会返回某种类型的函子,它运算符()被重载以支持“链接”(这是一种非常有用的技术,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); a(7);或多或少相同。

相关问题