【问题标题】:What is this programming technique? (Boost Library)这是什么编程技术? (升压库)
【发布时间】:2009-05-01 01:08:16
【问题描述】:

我正在尝试从 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() 可能是一个函数调用,但另一个 () 如何适合这里?这是某种运算符重载吗?

谢谢!

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    “add_options()”函数实际上返回了一个functor,也就是一个覆盖了()操作符的对象。这意味着下面的函数调用

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

    实际上扩展为

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

    “operator()”也返回一个函子,这样调用就可以像你展示的那样被链接起来。

    【讨论】:

      【解决方案2】:

      大概 add_options() 返回某种具有 operator() 重载以支持“链接”的函子(顺便说一句,这是一种非常有用的技术)

      重载 (...) 允许您创建一个像函数一样工作的类。

      例如:

      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); 相同。

      【讨论】:

      • 不错的答案。如果您和/或任何人可以扩展为什么链接“非常有用”,那将使这变得完整......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多