简体   繁体   中英

c++ class with templates compilation error

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.

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.

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

export template<typename foo>...

However, most compilers don't support this. The C++ FAQ has some more info: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.14

See JaredPar's answer for something that's actually reliable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM