I want to implement template function which will transform vector<A> to vector<B> by calling method A::fun() which returns type B.
I implemented it this way:
#include <algorithm>
#include <iostream>
#include <vector>
struct Point {
float x;
float y;
};
template<typename T, typename U>
std::vector<T> getVectorOfValues(const std::vector<U> &objects,
T(*functor)(const U&)) {
std::vector<T> result;
std::transform(std::begin(objects), std::end(objects), std::back_inserter(result), functor);
return result;
}
int main()
{
std::vector<Point> a = { {1,2},{3,4},{5,6},{7,8},{9,10} };
auto y = getVectorOfValues(a, +[](const Point& l){return l.y;});
for(auto a : y) { std::cout << a << " "; }
std::cout << std::endl;
}
It works well untill I need to capture variables by lambda and I have to put +
before lambda.
Why does the +
sign helps there?
Also I tried to use std::function but it couldn't deduce return type of functor without explicit declaration. How can I implement this idea in the way where return type of the functor is deduced automaticaly?