0

In my main I create an object from a template class, then I call my sort method (template method) However it get a error in my main.obj file.

error:

LNK2019: unresolved external symbol "public: void __thiscall SelectionSort<int [0]>::IterativeSort(int * const,unsigned int)" ............

Call in main:

SelectionSort<int[]> smallArraySort;
smallArraySort.IterativeSort(smallArray, smallSize);

Header file: SelectionSort.h

template <class T>
class SelectionSort
{
    public:
        void IterativeSort(T data, unsigned int size);
        void RecursiveSort(T data, unsigned int size);

};

sort code: SelectionSort.cpp

#include "SelectionSort.h"

template<class T>
void SelectionSort<T> ::IterativeSort(T data, unsigned int size)
{
    int temp = data[0];
    int greaterNum = 0


        for (unsigned int index = 0; index < size; index++)
    {
        for (unsigned int inner = index; inner < size; inner++)
        {
            if (temp>data[inner])
            {
                greaterNum = temp;
                temp = data[inner];
                data[inner] = greaterNum;

            }


        }
    }
}
monkey doodle
  • 690
  • 5
  • 12
  • 22
  • Lets ask that a little differently: Is the *implementation* of `SelectionSort::IterativeSort` as you have posted it here, in a header included within `main.cpp` (or whatever you called it)? I.e its *not* implemented (as you have it here) in some other .cpp file, *right* ? – WhozCraig Oct 18 '14 at 06:34
  • Well, your update with file names answers that question. [See this question](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – WhozCraig Oct 18 '14 at 06:48

1 Answers1

1

This happens because you implement the methods of the template in a .cpp file where they cannot be seen when they need to be instantiated. In general, templates must be defined in a header file.

To solve the problem, eliminate your SelectionSort.cpp file by moving its definitions into SelectionSort.h.

Community
  • 1
  • 1
cdhowie
  • 158,093
  • 24
  • 286
  • 300