vendredi 4 mars 2016

Template specialization with classes

I am trying to implement Template specialization. I delcared template and class:

template <class T>
class Person{

public:

        Person(char one, T two){

            this -> prv  = one;
            this -> druh = two;

        }
        void explain();

private:

    char prv;
    T druh;

};

and declared its getter

template <class T>

void Person<T>::explain(){

    cout << "Druh isnt char" << endl;

}

Now if i create object with data type other than char , it will indeeed output the "Druh isnt char" e.g

 Person <int> obj('a',5);    
 obj1.explain();  // "Druh isnt char"

I want to use specialization , so when the 2nd argument is char it will say "Druh is char"

I tried it using :

/********* Template specialization ***********/

template<>

class Person<char>{

public:
        Person(char one, char two){

           this-> prv = one;
           this-> druh = two;

        }
        void explain();

};

and defined explain method again

void Person<char>::explain(){

    cout << "Druh is a char " << endl;

}

But i am getting this error

'class Person' has no member named 'prv'|

Why is this happening? Should it take the private variables from first declaration of class Person? Doesnt templat<> says to compiler that i am not creating another Object just using template specification?

Aucun commentaire:

Enregistrer un commentaire