0

Possible Duplicate:
Why can templates only be implemented in the header file?
Undefined reference to template members
c++ template and header files

I am getting a compiler error when using a function template in a class. The function template was declared in a namespace in a separate source and header file.

Here is some example code.

namespace A header file

namespace A {

...
...
 template<typename T1, typename T2 >
 bool OR(T1* j, vector<T2*>, float cut);

...
...
}

A cpp file

namespace A {

 ...
 ...
  template<typename T1, typename T2 >
  bool OR(T1* j, vector<T2*>, float cut){

      ....
      ....

  }

 }

I then use this namespace in a class

class B cpp file ( only member function)

#include "A.h"

void B::exmaple(){


    if(A::OR(m_ptrObj, m_ptrvectortoOtherObj, m_cut)){

       cout  << "its true" << endl;

    }

 }

So the compiler error I get is as follows (Note this is the error from my real code, but same idea).

undefined reference to `bool JetFilters::OR<Jet, Jet>(Jet*, std::vector<Jet*, std::allocator<Jet*> >*, float)

Any ideas why I am getting the above error??

Community
  • 1
  • 1
MWright
  • 1,681
  • 3
  • 19
  • 31

2 Answers2

2

For an implicit instantiation of the template to work, the template must be visible at the place of instantiation. That is, when you use OR, the function template definition must be seen by the compiler. This is most often achieved by defining the function template in the header file.

Alternatively you can explicitly instantiate the OR template inside the A.cpp file for those types that will be used in the product, but this becomes a maintenance burden quite soon in most cases (as you will have to edit/recompile A.cpp for every use of the template with a new type)

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
1

When compiling A.cpp, the compiler doesn't know which instantiations must be generated for OR. So you have to either put OR into the header file or instantiate it explicitely in A.cpp:

template bool OR<Jet,Jet>(Jet*, vector<Jet*>, float);
thiton
  • 35,651
  • 4
  • 70
  • 100