Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why conversion operator is getting called when std::for_each() returns?

Tags:

c++

c++11

stl

I am learning functors and their usages. I came across below code in one of stack overflow questions.

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

class CalculateAverage
{
private:
   std::size_t num;
   double sum;

public:    
   CalculateAverage() : num (0) , sum (0)
   {
   }

   void operator()(int elem) 
   {
      num++;
      sum += elem;
   }

   operator double () const
   {
       return sum / num;
   }
};

int main()
{
    vector<int> values;

    for (int i = 1; i <= 5; i++)
        values.push_back(i);

    int average = std::for_each(values.begin(), values.end(), CalculateAverage());

    cout << average << endl;
}

Output : 3

I understood functor concept. But I didn't understand why conversion function is getting called. std::for_each() returns the same function that we pass to for_each() as the last argument. Here we are passing () overloaded function. Can some one please help me to understand why conversion function is getting called in this case?

like image 638
kadina Avatar asked Feb 18 '26 23:02

kadina


1 Answers

You are not passing a function to std::for_each, you are passing a functor (an object that acts like a function). When std::for_each returns it returns the function object you passed it. Your function object is of type CalculateAverage but you are trying to assign it to an int. So the conversion operator is chosen to convert the returned CalculateAverage into a double and then that is used to initialize average.

like image 149
NathanOliver Avatar answered Feb 20 '26 11:02

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!