Nested C++ template parameters for functions
std::vector
has two parameters, type and allocator.
Try this
template <typename T, typename Alloc, template <typename, typename> class V>
void print_container(V<T, Alloc> &con)
{
}
print_container(vec);
This will work for vector
, list
, etc., but will not work with map
, set
.
However, since you use auto
you can use C++11 and then you can to this:
template <typename T, template <typename, typename...> class V, typename... Args>
void print_container(V<T, Args...> &con)
or
template <template <typename, typename...> class V, typename... Args>
void print_container(V<Args...> &con)
and of course most simple way is to do something like
template<typename C>
void print_container(C& con)
probably with some checks for deduce, that C
is really container.
template<typename C>
auto print_container(C& con) -> decltype(con.begin(), void())
You're better off not doing that at all; consider just templating on the container
template <typename C>
void print_container(const C& container)
{
for(auto v: container)
std::cout << v << " ";
std::cout << std::endl;
}
If you need the stored type in the function, you can use: `typedef typename C::value_type T;
I am not sure that I understood what you want but you can try this:
template <typename V>
void print_vector(V &vec)
{
for(auto v: vec)
std::cout << v << " ";
std::cout << std::endl;
}
...
std::vector<double> vec(5);
...
print_vector(vec);
The point here is that usually you don't need construct like template < template V< typename T> >
because whole template template V< typename T>
can be generalized to type V
.