Lambda Expression vs Functor in C++

后端 未结 8 782
予麋鹿
予麋鹿 2020-12-05 00:01

I wonder where should we use lambda expression over functor in C++. To me, these two techniques are basically the same, even functor is more elegant and cleaner tha

8条回答
  •  生来不讨喜
    2020-12-05 00:35

    1) It's trivial and trying to share it is more work than benefit.

    2) Defining a functor simply adds complexity (due to having to make a bunch of member variables and crap).

    If neither of those things is true then maybe you should think about defining a functor.

    Edit: it seems to be that you need an example of when it would be nice to use a lambda over a functor. Here you go:

    typedef std::vector< std::pair > whatsit_t;
    
    int find_it(std::string value, whatsit_t const& stuff)
    {
      auto fit = std::find_if(stuff.begin(), stuff.end(), [value](whatsit_t::value_type const& vt) -> bool { return vt.second == value; });
    
      if (fit == stuff.end()) throw std::wtf_error();
    
      return fit->first;
    }
    

    Without lambdas you'd have to use something that similarly constructs a functor on the spot or write an externally linkable functor object for something that's annoyingly trivial.

    BTW, I think maybe wtf_error is an extension.

提交回复
热议问题