Greetings.
I don't know very well how to explain myself, but I believe a piece of code will make you understand what I'm intenting to do :
template<class A, class B>
void myFunction(A<B>& list)
{
typename A<B>::iterator current = list.begin();
typename A<B>::iterator end = list.end();
while (current != end)
{
current++;
}
}
Where A is an STL container (vector, list...). It's like inception, but with templates : a template, inside a template, etc...
The thing is : what do you do when one of the params of your template is itself a template... and still want to support every types supported by this template.
This of course doesn't compile (it says 'A is not a template').
Does someone knows how to create such a template ?
You are looking for a template template parameter
template<template<class T, class All = std::allocator<T> > class A, class B>
void myFunction(A<B>& list)
{
typename A<B>::iterator current = list.begin();
typename A<B>::iterator end = list.end();
while (current != end)
{
current++;
}
}
However, in your particular case, I think you'd be better off by just passing the intantiated container, that is,
template<class C>
void myFunction(C& list)
{
...
}
use like this
vector<char> v;
myFunction(v);
Your original code would have to be called like this:
myFunction<std::vector, char> (v)
which is much more verbose and has no particular benefit
A
and B
will be concrete types (and not templates), thus A<B>
makes no sense.
You can write your code this way:
template<class List>
void myFunction(List &list)
{
typename List::iterator current = list.begin();
typename List::iterator end = list.end();
while (current != end)
{
current++;
}
}
If you need to know what is the type of an element of that list, there is a typedef inside of the list for that:
typename List::value_type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With