2

Stroustrup gives the example of using an overloaded operator() to execute a function on vector elements during a transform operation:

class Example
{
  public:
   std::vector<int> Test1 {1,2,3,4,5};
   std::vector<int> Test2;
   int operator()(int el);
   void MyFunction();
}

int Example::operator()(int el)
{
  return el + 1;
}

void Example::MyFunction()
{
std::transform(Test1.begin(), Test1.end(), std::back_inserter(Test2), std::bind(Example(), std::placeholders::_1))
}

However, with the introduction of lambda expressions the above code seems very verbose, compared to:

std::transform(Test1.begin(), Test1.end(), std::back_inserter(Test2), [](int el){return el + 1;});

Am I right in saying there is little value in using the overloaded operator() approach? Or are there still scenarios where they can be beneficial when working with STL algorithms?

SergeyA
  • 61,605
  • 5
  • 78
  • 137
Babra Cunningham
  • 2,949
  • 1
  • 23
  • 50
  • Your title is generic - operator overloading - but you actually mean operator() overloading, and even more precisely, using functors. I will edit the question. – SergeyA Dec 09 '16 at 19:07
  • 1
    Why are you using `std::bind` in your first example? – Deduplicator Dec 09 '16 at 19:16

2 Answers2

2

Yes you're right.

A lambda expression basically creates a nameless functor. It just allows the programmer to do it in less code. Before C++11 the standard algorithms could only work with functors which would require the programmer to set up a whole new class just for some specific behaviour (like you just did).

This is exactly the reason why lambda's were introduced into C++11, to make sure using the standard algorithms with a custom functor weren't such a pain to write anymore.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

As Gill Bates mentions, you are correct, the lambda expression does create a nameless functor. However, it can also makes code considerably more difficult to read. I've found that, in collaborative projects, it's often clearer to just overload the operator if something is used more than once, especially if something complicated is going on.

On that note, lambdas are good if you use them sparingly. For functionality that is vital and often used with your object, you may want to encapsulate all such interactions in an overloaded operator.

Nikos Kazazakis
  • 792
  • 5
  • 19