mercredi 11 octobre 2017

C++ why does using a function object argument in std::transform fail and require a lambda expression instead

From this question I got a good understanding of functors (function objects); how to initialize and call them. I wrote some code to play around with this for my own understanding

class Foo
{
private:
   int x;
public:
   Foo(int x) : x(x) {}
   int operator()(int y) { return x + y; }
};

std::vector<int> vec(10);
std::vector<int> pec(10);

std::transform(vec.begin(), vec.end(), vec.begin(), poo(1));

and receive the following compilation error

Severity Code Description Project File Line Suppression State Error C2064 term does not evaluate to a function taking 1 arguments

I looked within the above question at some of the comments and tried a lambda expression instead

std::transform(vec.begin(), vec.end(), vec.begin(), [](Foo poo) {return poo(1); });

which works but I don't understand why the accepted answer using std::transform(in.begin(), in.end(), out.begin(), add_x(1)); fails. Why do I have to use a lambda expression? Another answer is doing the same thing but it still will result in a compilation error. Why is that?

Aucun commentaire:

Enregistrer un commentaire