Can anybody explain what is a "Template Specialization" and how it is useful
and what is the use of "typename"
Template specialisation is when you define a separate for some type:
#include <iostream>
template<class T>
struct Foo
{
void print();
};
template<class T>
void Foo<T>:
rint()
{
std::cout << "Generic print\n";
}
template<>
void Foo<int>:
rint()
{
std::cout << "int print\n";
}
int main()
{
Foo<int> fi;
Foo<char> fc;
fi.print();
fc.print();
}
There I have specialised Foo for int so that it will use another
implementation of print(). This can be useful among other things if you
know that for some types you can make a more efficient implementation
than then generic implementation.
A (failed) example of this is std::vector<bool>, which was specialised
to reduce the memory needed to store the elements, but unfortunately it
does not have the same behaviour as std::vector for other types. Having
a different behaviour can sometimes be desirable, but not for a container.
See also sections 35.7 and forward in the FAQ:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.7
typename can be used to tell the compiler that something is a type (and
not an object or function), in certain situations the compiler can not
figure this out by itself. The FAQ have an excellent description of
this:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18