0

This is strange. How can it possibly be that I get an error when I'm including an .h file (GeneralSearch.h) but everything seems to work just fine when, instead, I include the .cpp file (GeneralSearch.cpp)?

.h file

#ifndef GENERALSEARCH_H_
#define GENERALSEARCH_H_

#include "Problem.h"
#include "Node.h"

template <class T>
class GeneralSearch
{
public:

    const Node* treeSearch(const Problem &problem) const;
    const Node* graphSearch(const Problem &problem, T &fringe = T()) const;

private:
    void expand(const Node &node, const Problem &problem, list<const Node*> &out) const;
};

#endif

.cpp file

#include "GeneralSearch.h"
template <class T>
void GeneralSearch<T>::expand(const Node &node, const Problem &problem, list<const Node*> &out) const
{
...
}

template <typename T>
const Node* GeneralSearch<T>::treeSearch(const Problem &problem) const
{
...
}

template <typename T>
const Node* GeneralSearch<T>::graphSearch(const Problem &problem, T &fringe = T()) const
{
...
}

the program file - WORKING

#include "GeneralSearch.cpp"
#include "DummyProblem.h"
#include "DepthFirstSearch.h"
#include <queue>

int main (int argc, char* argv[]){}

the program file - NOT WORKING

#include "GeneralSearch.h"
#include "DummyProblem.h"
#include "DepthFirstSearch.h"
#include <queue>

int main (int argc, char* argv[]){}
  • 4
    possible duplicate of [Linker error when using a template class?](http://stackoverflow.com/questions/9171494/linker-error-when-using-a-template-class); this is asked very regularly. – Mat May 05 '12 at 07:31
  • error LNK2019: unresolved external symbol "public: class Node const * __thiscall GeneralSearch > > >::graphSearch(class Problem const &,class std::stack > > &)const " (?graphSearch@?$GeneralSearch@V?$stack@PBVNode@@V?$deque@PBVNode@@V?$allocator@PBVNode@@@std@@@std@@@std@@@@QBEPBVNode@@ABVProblem@@AAV?$stack@PBVNode@@V?$deque@PBVNode@@V?$allocator@PBVNode@@@std@@@std@@@std@@@Z) – wolfovercats May 05 '12 at 07:31
  • referenced in function "public: class Node const * __thiscall DepthFirstSearch::Search(class Problem const &)const " (?Search@DepthFirstSearch@@QBEPBVNode@@ABVProblem@@@Z) – wolfovercats May 05 '12 at 07:31
  • @Mat it seems you're right. How didn't I find this?? (thanks!) – wolfovercats May 05 '12 at 07:34
  • This answers my question. http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – wolfovercats May 05 '12 at 22:36

1 Answers1

1

The linker tries to find the definitions of unresolved names while linking. In the second case, the linker is not able to find the definitions of the member functions of the class GeneralSearch and hence you get the error.

bisarch
  • 1,388
  • 15
  • 31