Thursday, August 4, 2016

Class Template Specialization


Class Template Specialization


in some cases it is possible to override the template-generated code by providing special definitions for specific types. this is called Template Specialization.
the following example defines a template class specialization for template class stream.

////TTT.h#include <iostream>using namespace std;
template<typename T>class stream{  public:    void f() {cout << "stream<T>::f()"<<endl;}};
template<>class stream<char>{  public:    void f() {cout << "stream<char>::f()"<<endl;}};
////main.cpp#include "TTT.h"int main(){  stream<int>  si;  stream<char> sc;
  si.f();////--> stream<T>::f()  sc.f();////--> stream<char>::f()
  return 0;}

In the above example, stream<char> is used as the definition of streams of chars; other streams will be handled by the template class generated from the class template.


,,,



No comments:

Post a Comment