Code About Us Tutorial


  Templates
    Template Functions
    Multiple Template Parameters
    Template Specialization
    Class Templates
    Linked List
    Linked List Template
    Binary Tree


   
 

Home > Templates > Template Specialization

November 26, 2009 9:02 pm

   

Template Specialization

Now coming back to C-style strings, since these heavily depend on pointers, they require a special case. You are allowed to make templates of explicit classes; doing so is called template specialization. Thus, the following is a valid addition to our above form except this one specializes in "char*" (pointer to type char) and overrides the above template when using char* as the template parameter:

 

 
template <char* T>
void swap (T rx, T ry)
{
	T temp = rx[ 0 ];
	for( int i = 0; i < length; i++ )
	{
		temp = rx[ i ];
rx[ i ] = ry[ i ];
		ry[ i ] = temp;
	}
}

Now if you call the function swap using "char*" as your type, it will call the second the explicit form instead of the first form. Another thing about templates is that they are just an addition to existing classes or functions. I will talk about the class form later on.

You can also call Template functions the following:

 

 
template <class T>              // The most usual: one class parameter.
template <class T, class E>     // Two class parameters.
template <class T, long L>       // A class and a long.
template <class T = int>       // an int as a default parameter.
template <int foo (void)>      // A function as parameter.
template <char* T>                // pointer to char as a parameter.
Please Rate this Code:


    Comments for: Template Specialization
Annonymouse User says:
Precicely what I was looking for. Short and with the background I needed to know. Good work.

MoMad [big_mo_mine@yahoo.com] Posted: 31 times. says:
The function as a parameter should be a pointer to a function like this:

 
 
template <int (*foo) (void)> 

And the name of the template type (in this case function pointer), would be foo. You would use it like this:

 
 
template <int (*foo) (void)> 
class CallBack {
  void Call() {
    cout << "foo says: " << foo() << endl;
  }
};

int SayHello() { cout << "Hello Stranger... " << endl; return 1337; }

CallBack<SayHello> cB; cB.Call();

// Will produce: // Hello Stranger... // foo says: 1337





Add Comment:
Name:
Email:


 «61» THINKQUEST TEAM C0111571 © 2001. All Rights Reserved.