I have a custom vector class that for all purposes and tasks acts like std :: vector. I want to add a simple map function:
template <class T> class Vector { public: template<class mapFunction> Vector<typename mapFunction::result_type> map(mapFunction function) { Vector<mapFunction::result_type> result(_Length); for(UINT i = 0; i < _Length; i++) { result[i] = function(_Data[i]); } return result; } ... }
Using:
Vector<int> v(5); for(int i = 0; i < 5; i++) v[i] = i; auto mappedVector = v.map(function<double(int)>([](int a) { return a * 2.0; }));
This works, but I try to avoid the need to cast an expression from a lambda expression to std::function
. Ideally, this would be just v.map([](int a) { return a * 2.0; }));
I understand that probably I could write a "make_function" like "make_pair" to avoid the need for template parameters, but you still need to discard all your lambdas.
I passed it to std::function
because I don't know how to extract the return type from the raw lambda type; so i am using std::function::result_type
.
I thought the following would work, but it wasn’t - the compiler simply complains that it cannot output the template argument for "returnType":
template<class mapFunction, class returnType> Vector<returnType> Map2(mapFunction function) { Vector<returnType> result(_Length); for(UINT i = 0; i < _Length; i++) { result[i] = function(_Data[i]); } return result; }
I understand that std::transform
does this (I can easily replace the map body with a call to std::transform
), but my problem is really with the correct way to specify template parameters.
source share