Possible Duplicate:
template<> in c++
I have seen template<>
in c++ code.
Is this valid syntax? If it is, what does it mean?
Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort (), max (), min (), printArray (). // One function works for all data types. This would work Below is the program to implement Bubble Sort using templates in C++: // A template function to implement bubble sort.
Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
It is possible in C++ to get a special behavior for a particular data type. This is called template specialization. Template allows us to define generic classes and generic functions and thus provide support for generic programming.
I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?
It's used whenever you explicitly specialize a template (class or function template) or a member of a class template. The first set of examples use this class template and members:
template<typename T>
struct A {
void f();
template<typename U>
void g();
struct B {
void h();
};
template<typename U>
struct C {
void h();
};
};
// define A<T>::f() */
template<typename T>
void A<T>::f() {
}
// specialize member A<T>::f() for T = int */
template<>
void A<int>::f() {
}
// specialize member A<T>::g() for T = float
template<>
template<typename T>
void A<float>::g() {
}
// specialize member A<T>::g for T = float and
// U = int
template<>
template<>
void A<float>::g<int>() {
}
// specialize A<T>::B for T = int
template<>
struct A<int>::B {
/* different members may appear here! */
void i();
};
/* defining A<int>::B::i. This is not a specialization,
* hence no template<>! */
void A<int>::B::i() {
}
/* specialize A<T>::C for T = int */
template<>
template<typename U>
struct A<int>::C {
/* different members may appear here! */
void i();
};
/* defining A<int>::C<U>::i. This is not a specialization,
* BUT WE STILL NEED template<>.
* That's because some of the nested templates are still unspecialized.
*/
template<>
template<typename U>
void A<int>::C<U>::i() {
}
template<typename T>
struct C {
void h();
};
/* explicitly specialize 'C' */
template<>
struct C<int> {
/* different members may appear here */
void h(int);
};
/* define void C<int>::h(int). Not a specialization, hence no template<>! */
void C<int>::h(int) {
}
/* define void C<T>::h(). */
template<typename T>
void C<T>::h() {
}
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