ElfsЯUs
ElfsЯUs

Reputation: 1218

Problem using templates in C++

I am using templates for the first time in C++ and running into a problem when I try to compile. Basically trying to create my own basic ArrayList of sorts:

The .hpp:

#ifndef ARRAYLIST_HPP_
#define ARRAYLIST_HPP_

template <class T>
class ArrayList
{
    private:
        int current, top ;
        T * al ;

    public:
        ArrayList() ;   // default constructor is the only one
};

#endif /* ARRAYLIST_HPP_ */

The .cpp:

#include "ArrayList.hpp"

using namespace std ;

//template <class T>
//void memoryAllocator( T * p, int * n ) ; // private helper functions headers

template <class T>
ArrayList<T>::ArrayList()
{
    current = 0 ;
    top = 10 ;
    al = new T[top] ;
}

The main:

#include "ArrayList.hpp"

int main()
{
    ArrayList<int> test ;
}

When I try to build without the main it compiles fine, however, as soon as I try to use it in the main I get the following error:

Undefined symbols for architecture x86_64:
  "ArrayList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::ArrayList()", referenced from:
      _main in Website.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [APProject2] Error 1

Any thoughts as to what might be the problem would be much appreciated!

Cheers!

Upvotes: 2

Views: 2839

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106096

You can't put the templated code into a separate .cpp file... your constructor should be in the ArrayList header. The point is that it's only when main() is compiled that the compiler realises it needs to instantiate ArrayList and what type T will take, and so it needs to have the code available to do the instantiation....

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

You need to include the implementation in the .hpp file. The compiler needs to know T at compile time to generate the specialization.

Upvotes: 3

pmr
pmr

Reputation: 59811

Templates need to be declared and defined in the header.

Also: I don't think that is the real error. It mentions an instantiation of ArrayList<std::string> which I can't see anywhere.

This FAQ entry explains why.

Upvotes: 4

Related Questions