C ++ class with template compilation error

I am not an experienced C ++ programmer and I am having compilation problems. I have a heap class that uses a template:

template <class T>
class Heap
{
  public:
    Heap(const vector<T>& values);

  private:
    vector<T> d;

  // etc.
};

      

And then into a separate implementation file:

template <class T>
Heap<T>::Heap(const vector<T>& values)
{
d = values;

for (unsigned int i = d.size()-1; i > 0; i--) Heapify(ParentIndex(i));
}

// ... more implementation code ...

      

And finally, the main.cc file:

int main (int argc, char *argv[])
{
  vector<int> in;
  unsigned int i;

  while (cin >> i) in.push_back(i);
  Heap<int> h = Heap<int>(in);

  return 0;
} 

      

I am getting these compilation errors:

g++ -Wall -I/opt/local/include -c -o main.o main.cc
g++ -Wall -I/opt/local/include -c -o heap.o heap.cc
g++ -Wall -o heap main.o heap.o
Undefined symbols:
  "Heap<int>::Heap(std::vector<int, std::allocator<int> > const&)", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [heap] Error 1

      

Why doesn't it compile? I think the linker is saying that it cannot find the constructor, but I know that it made an object file.

+2


source to share


2 answers


Templates must be defined in the header file 100%. If you have an implementation Heap<T>

in your .cc / .cpp file that is the problem. Move all the code into a header file and it should fix your problem.



+8


source


According to the C ++ standard, you can use the keyword export

like this:

export template<typename foo>...

      



However, most compilers do not support this. The C ++ FAQ has more information: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.14

See JaredPar's answer for a really reliable one.

+3


source







All Articles