-2

Possible Duplicate:
C++ templates, undefined reference

I have a problem with a template constructor function. I want to use a template in the constructor function without a template class, something like this:

test.h

class test {
   public:

   template <class T>
   test(T* obj);
};

test.cpp

template <class T>
test::test(T* obj) {
   /* ... */
}

main.cpp

int main() {
   int    y = 5;
   test*  o = new test(yy);
   delete o;
}

When I attempt to build this in MSVS I get error lnk2019 ("unresolved external symbol").

I found that the solution is to define the constructor function in the header file like this:

test.h

class test {
   public:

   template <class T>
   test(T* obj) { /* some code here */ }; 
};

or like this:

test.h

class test {
   public:

   template <class T>
   test(T* obj);
};

template <class T>
test::test(T* obj) {
  /* some code here */
}

Is there in way to write the template function in a separate .cpp file? Or must I define it in the header file?

Community
  • 1
  • 1
user722528
  • 667
  • 1
  • 6
  • 11

1 Answers1

1

Unfortunately if you want to use the template function anywhere other than the module it is declared in (test.cpp in your example) then you must define the function as well as declare it in the header file.

David Snape
  • 225
  • 2
  • 9