Template specialization

A

AS

Can anybody explain what is a "Template Specialization" and how it is useful
and what is the use of "typename"

Thanks
AS
 
E

Erik Wikström

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>::print()
{
std::cout << "Generic print\n";
}

template<>
void Foo<int>::print()
{
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,184
Messages
2,570,976
Members
47,536
Latest member
MistyLough

Latest Threads

Top