I am teaching myself template programming in C++, so some of my assumptions may be wrong – please correct me if you see any errors.
I am trying to use an STL list as a template parameter to a function. The function is supposed to be used with all sorts of data types, so I have defined the function as template<class T> rather than template<template<> class T> in its original declaration. I now want to specialise it to support a template class.
template<class T>
void function(T param)
{
// do something with T
}
template<template <class T, class Allocator> class listPlaceholder>
void function(std::list<T, Allocator> param)
{
// do something with every element in param (I actually need to know it's a list)
std::list<T, Allocator>::iterator current = param.begin();
std::list<T, Allocator>::iterator end = param.end();
do {
function<T>(*current);
} while (++current != end);
}
The problem is that when I try to compile this code (under GCC) it says that T and Allocator are not defined in the scope. My primary question is “how do I specialise for template classes?” and secondly, if it is possible, “how do I extract the template template parameters?”.
As mentioned previously, I am learning template programming, so obvious solutions are welcome.
You want to declare those parameters
The names you used in the formal parameter list have no meaning. You also forgot to use
listPlaceholderactually. But I’m assuming that was accidental.As another poster said, you also need the
typenamekeyword because the names are dependent names.For why the names in the formal list are meaningless, compare it to function pointers:
What is important is only the type of the parameters, and I could have written
void(*p)(int, int)too. In your case, what is important is only that both parameters are type parameters. So you could have written the template template parameter also astemplate<class, class> class listPlaceholdertoo, completely equivalent.Last but not least, I would like to emphasize that you have not specialized
function, but you have overloaded it with another template. So, bothfunctions are two completely different function templates.