Whats wrong with templates?

1
2
3
4
5
6
7
8
9
10
/* saved as mypair.cpp */
#include "mypair.h"

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}


1
2
3
4
5
6
7
8
9
/* saved as mypair.h */
template <class T>
class mypair {
    T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}
    T getmax ();
};


1
2
3
4
5
6
7
8
9
10
/* saved as sample.cpp */
#include <iostream>
using namespace std;
#include "mypair.h"

int main () {
  mypair <int> myobject (100, 75);
  cout << myobject.getmax();
  return 0;
}




why does this error occur when i try to build this?

error LNK2019: unresolved external symbol "public: int __thiscall mypair<int>::getmax(void)" (?getmax@?$mypair@H@@QAEHXZ) referenced in function _main Sample.obj Sample
closed account (z05DSL3A)
Don't put template code in a .cpp file, put it all in the .h file.

See: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
Last edited on
aw.. is that it? because i am used in putting all the definitions of my class in a .cpp file and the prototypes in a .h file.. but anyways, is there any possible way to define a template in .cpp file?
Nope. Think about it. If it's in a cpp file, you have to compile it. And how can the compiler do that when it doesn't know which types the template will be used with?

The entire template class, definition and implementation must be visible in code to the compiler when it compiles code using the template class.

You can, of course, put your implementations into a separate .inl file or something, and then include that at the bottom of the template header file:
1
2
3
4
5
6
7
8
9
10
11
12
13
// Class.hpp
template <class T> class holder { 
   T value;
public:
   T& Get();
   void Set(T&);
};

#include "Class.inl"

// Class.inl
template <class T> T& holder<T>::Get() { return value; }
template <class T> void holder<T>::Set(T& t) { value = t; }
Last edited on
great.. thanks.. now im beggining to use .inl files to keep my header files clean.. ^_^..
Topic archived. No new replies allowed.