#include <vector>
#include <iostream>
#include <algorithm>
class Funct
{
int Total;
public:
Funct() : Total(0) {};
voidoperator() (int& i )
{
Total += i;
}
} funct;
int main()
{
std::vector<int> v = {1,5};
int sum = std::for_each(v.begin(),v.end(),funct); //Error here
std::cout<<"The total is "<<sum<<".\n";
}
You shall use funct()
Oops, I am sorry. I did not see that you already defined the object.
The problem is that your operator function does not return anything. And you are trying assign a pointer to fucntion to int. You can redefine your class the following way
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class Funct
{
int Total;
public:
Funct() : Total(0) {};
voidoperator() (int& i )
{
Total += i;
}
int get_total() const
{
return ( Total );
}
} funct;
And then call
1 2
std::for_each(v.begin(),v.end(),funct);
int sum = func.get_total();
Or
int sum = std::for_each(v.begin(),v.end(),funct).get_total();
Thanks, that worked but i'm confused.
According to the documentation, std::for_each has the same return type as the functor.
our function returned void, so how did we call the get_total() method on it?
According to the documentation, std::for_each has the same return type as the functor.
our function returned void, so how did we call the get_total() method on it?
The algorithm returns what was passed to it. As you are passing the object it is returned. If you would pass a pointer to function it were returned.
Your last code shall not be compiled because the object is returned.
You could change your class the following way adding the conversion operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Funct
{
int mTotal;
public:
Funct() : mTotal(0) {};
intoperator() (int& i )
{
return (mTotal += i);
}
operatorint() const
{
return ( mTotali);
}
} funct;