0

I have a templatized class definition in test.hpp

///////////////////////////////////////////////
class point1 {
public:
int z0;

point1(): z0(1)
{}
};
///////////////////////////////////////////////
class point2 {
public:
int z1;

point2(): z1(2)
{}
};
///////////////////////////////////////////////

template <class T>
class line {

public:
T p1;

void printPoint(void);
};

and in implementation file test.cpp I am trying to specialize the printPoint function of class line

 ///////////////////////////////////////////////
 template<>
 void line<point1>::printPoint(void)
 {
cout<<p1.z0<<endl;
 }

 template <class T>
 void line<T>::printPoint(void)
 {
cout<<p1.z1<<endl;
 }
 //////////////////////////////////////

and main function is in testmain.cpp

 int main()
 {
line<point1> r1;
line<point2> r2;

r1.printPoint();
r2.printPoint();


int abc;
cin>>abc;
return 0;
 }

But linker throwing error that printPoint function is multiply defined. Is it a correct way of member function specialization of a class if not than how to specialize member function of a templatized class? Please help.

tod
  • 81
  • 1
  • 6
  • @StoryTeller I disagree. OP is going to hit that problem later but the current problem is that he puts template definitions into `.cpp` files. – pmr Dec 17 '13 at 13:18

1 Answers1

1

Because the type T is only known when you instantiate the line class with some tipe, it's impossible for the compiler to know in the cpp file the generic type T that will be used later on so it can't compile those functions. That's why you first need to move the implementation of those function in the header file:

template <class T>
class line {

public:
    T p1;

    void printPoint(void)
    {
        cout<<p1.z1<<endl;
    }
};

Now, the above implementation is for a generic type T, and now if you want it for special type , say point1:

 template <>
class line <point1> /*note this line changed*/ {

public:
    point1 p1;

    void printPoint(void)
    {
        cout<<p1.z0<<endl;
    }
};
Raxvan
  • 6,257
  • 2
  • 25
  • 46