Reputation: 11
I'm trying to write a function in C++ that takes, as parameter, a template container and returns a container of the same type but with integers. For example, I want to write a template function that generates functions like:
std::vector<int> foo(std::vector<std::string>);
std::vector<int> foo(std::vector<float>);
std::list<int> foo(std::list<float>);
The reason is that I'm trying to write a template function in C++ that is equivalent to map in JavaScript (eg: given an array of objects and a function that transforms the object in an integer, returns an array of integers).
Is there a way of doing this in C++?
Upvotes: 0
Views: 66
Reputation: 42776
You can use template template parameter to do this:
template<template<class...> class C, class T>
C<int> foo(const C<T>&);
When you pass std::vector<float>
to foo
, C
and T
will be deduced as std::vector
and float
respectively, so C<int>
is std::vector<int>
.
Upvotes: 3