Sridhar Thiagarajan
Sridhar Thiagarajan

Reputation: 580

Template specialization example

To my understanding, template specialization works as follows

template<typename T> 
void dummy(T a) { std::cout<<a<<std::endl; }

template<>
void dummy<int>(int a) { std::cout<<"special"<<std::endl; }

I was looking at the following code which checks if something is a pointer or not:

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

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

Is this still a template specialization? Why is the line template <typename T> there again in the specialization, and not <>. Is it because multiple specializations are generated by the compiler whenever we have T* rather than T?

Would this code expand to

template<>
struct is_ptr<int*>
{
  constexpr static bool value = true;
};

?

Upvotes: 2

Views: 105

Answers (1)

rmawatson
rmawatson

Reputation: 1943

Your first example is a function template specialization. The is_ptr example is a partial class template specialization.

function templates cannot be paritially specailzied, class templates can be.

The reason for the template <typename T> in the class template partial specialization is precisely because it is specialized partially on pointers, but of any type T.

in your example when using is_ptr<int*>::value, the partial specialization will indeed be selected.

Upvotes: 4

Related Questions