c++ class with templates compilation error

c++, class, linker, templates

Solution

Templates need to be defined 100% within the header file. If you have your `Heap<T>` implementation in a .cc / .cpp file that is the problem. Move all of the code to the header file and it should fix your issue.

Problem

I'm not an experienced C++ programmer and I'm having problems compiling. I've got 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 in 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 a 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 get these compile 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 does this not compile? I think the linker is saying it can't find the constructor, but I know it made the object file.

Original source