bughi
bughi

Reputation: 1858

Template class specialization to handle its own type

I've been playing around with templates to get a feel for them and i wanted to do a class specialization on its own type. I searched the internet for a while but i found no mention of this.

For example if i have a class Array:

template<class T>
class Array{
 ...
 void print();
}

Is it possible to specialize method print() when T=Array<unspecified type>?

template<class T>
void Array<Array<T>>::print(){
    //do something diffrent for array of array
    //this code wont work
}

I managed to do this

template<>
void Array<Array<int>>::print(){
    //print in matrix format
    //this code works
}

I don't see this feature being extremely useful, but i was nonetheless curious

Upvotes: 3

Views: 240

Answers (2)

Puppy
Puppy

Reputation: 147036

There is a feature called partial specialization where you could apply something like this. However, I don't believe that you can partially specialize member functions without partially specializing the whole class.

Upvotes: 2

Matteo Italia
Matteo Italia

Reputation: 126957

AFAIK you can perform a specialization only for the whole class. Once I needed something like that (actually, I just needed two typedefs to be different), so I created an auxiliary class which contained only the members that had to be specialized, and made the principal class inherit from it.

Upvotes: 2

Related Questions