K. Kapelinski
K. Kapelinski

Reputation: 11

Is there a way to get a class template in C++ and use it to create another template?

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

Answers (1)

康桓瑋
康桓瑋

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>.

Demo.

Upvotes: 3

Related Questions