0

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?

libhet
  • 21
  • 2
  • Because lambda function is not a function, it's a functional object. It can be converted to a function pointer with the unary plus operator. The proper way to take a lambda is to add a template parameter `Fn` and then take `Fn functor`/`const Fn &functor`/`Fn &&functor` (if you're aware of perfect forwarding). – yeputons Dec 31 '22 at 02:15

0 Answers0