Aquarius_Girl
Aquarius_Girl

Reputation: 22916

Class Templates Partial Specialiazation

The following code compiles successfully, and I fail to understand why:

#include <stdio.h>
#include <vector>
#include <iostream>

// Template definition
template <typename T1, typename T2> class stack
{
};

// Template specialization
template <> class stack <float, float>
{
};

int main ()
{
  stack <char, char> objStack;
  return 0;
}    

Doesn't Partial Specialization mean that we can use the class for some particular data types, which we specify in the specializations?

There is no specialized class for char here, and if it is going to compile with any kind of data types then what is the purpose of specialization?

Upvotes: 0

Views: 104

Answers (2)

Jonathan Sterling
Jonathan Sterling

Reputation: 18375

Template specialization is for when you want to do something specifically different for specific template parameters. The compiler will instantiate anything non-speficied from the original template.

This is useful for when you want different behavior for a specific data type, but can also be used for more complex pattern matching, such as changing the behavior for pointer types, or const types:

template <typename T>
struct is_pointer { static bool value = false; };

template <typename T>
struct is_pointer<T*> { static bool value = true; };

template <typename T>
struct is_const { static bool value = false; };

template <typename T>
struct is_const<const T>  { static bool value = true; };

// later, try this:
assert(is_pointer<int*>::value == true);
assert(is_pointer<int>::value == false);

So, long story short: don't bother specifying your template unless you've got something special to do with a certain parameter, that you can't generalize into the base-template. Template specialization is just a rather hardcore form of pattern-matching which can be used for both good and evil.

Upvotes: 1

ltc
ltc

Reputation: 3361

Template specialization means taking a general purpose template and adding a type or function that will be used for a special set of types. Partial specialization is when you have a template type or function with more than one parameter and you do not specify all of the parameters in your specialization.

In your example, this function is the general template.

// Template definition
template <typename T1, typename T2> class stack
{
};

It will be instantiated for any types you give it EXCEPT for if you give two floats. In the case that you give two floats as parameters this template

// Template specialization
template <> class stack <float, float>
{
};

will be instantiated.

Upvotes: 1

Related Questions