Adding a map function to a vector in C++11
I have a custom vector class that for all intents and purposes acts just
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;
}
...
}
Usage:
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'm trying to avoid the need for the cast from a lambda
expression to std::function. Ideally it would just be v.map([](int a) {
return a * 2.0; })); I realize that I could probably write a
"make_function" similar to "make_pair" to avoid the need for template
parameters, but you'd still need to cast all your lambdas.
I cast it to a std::function because I don't know how to extract the
return type from a raw lambda type; hence I'm using
std::function::result_type.
I thought the following would work, but it doesn't -- the compiler just
complains that it cannot deduce 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 realize that std::transform does this (I could easily replace the body
of map with a call to std::transform), but my problem is really with the
right way to specify the template parameters.
No comments:
Post a Comment