【问题标题】:How is Boost able to achieve such syntax?Boost 是如何实现这样的语法的?
【发布时间】:2015-12-31 09:39:14
【问题描述】:

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")
;

是通过运算符重载吗?

如果是,这里重载了哪个运算符?

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

【问题讨论】:

  • 看起来像函数调用操作符,每次调用都返回同一个对象,其中operator()重载了一个新的选项。
  • @BoBTFish 因为这几乎是一个完整的答案,所以你可以这样发布:-P

标签: c++ boost


【解决方案1】:

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

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

您可以找到options_descriptionsoptions_description_easy_init here 的源代码。

要自己复制它,您可以执行以下操作:

#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;
}

【讨论】:

    【解决方案2】:

    希望这是不言自明的

    #include <iostream>
    
    class funky_counter
    {
    public:
        funky_counter() : value_(0) {}
    
    public:
        funky_counter & increment(int value)
        {
            value_ += value;
            return *this;
        }
    
    public:
        funky_counter & operator()(int value)
        {
            return this->increment(value);
        }
    
    public:
        int get_value() 
        { 
            return value_; 
        }
    
    private:
        int value_;
    };
    
    int main(void)
    {
        funky_counter counter;
    
        counter.increment(2) (5) (7);
    
        std::cout <<  counter.get_value() << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-09
      • 1970-01-01
      • 2020-04-01
      • 2011-05-11
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      相关资源
      最近更新 更多