I am trying to create a class Vec
and it contains method map
to return an new Vec
odject.
I want map
method can return different type (like Javascript's map function).
The error is found:
main.cpp:31:13: error: no matching member function for call to 'map'
numbers.map([](int &item)
~~~~~~~~^~~
main.cpp:18:12: note: candidate template ignored: couldn't infer template argument 'U'
Vec<U> map(Lambda lambda)
Here is my code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template <typename T>
class Vec
{
public:
std::vector<T> value;
Vec(std::vector<T> vector)
{
value = vector;
}
template <typename Lambda, typename U>
Vec<U> map(Lambda lambda)
{
std::vector<U> updatedValue;
std::transform(value.begin(), value.end(), std::back_inserter(updatedValue), lambda);
Vec<U> UpdatedVector(updatedValue);
return UpdatedVector;
}
};
int main()
{
Vec<int> numbers({10, 20, 30, 40, 50});
Vec<std::string> new_numbers = numbers.map([](auto &item)
{ return "new value is string"; });
// Value of the 'new_numbers.value' should be {"new value is string", "new value is string", "new value is string", "new value is string", "new value is string"}
return 0;
}