0

I am new to c++ and I am facing linker error with my code. I am trying to compile with Visual Studio 2019.

The error is as follows:

LNK2019 unresolved external symbol "public: void __thiscall SequenceList::display(void)" (?display@?$SequenceList@H@@QAEXXZ)

When I add #include "test.cpp" to my file, it runs successfully. I want to know if there is any better solutions.

//this is sequencetest.cpp
#include <iostream>
#include <string.h>
#include "test.h" 
using namespace std;

int main() 
{   SequenceList<int> List1; 
    List1.Input(); 
    List1.display();    
    return 0; 
}

//this is test.h

#pragma once
const int MaxSize = 20;

template <typename T>class SequenceList {
private:
    int _size;                              //the length of the list
    T* element;                             //save the data
    int MaxSizeNow;                         //the maxsize at present
public:
    SequenceList() { _size = 0; MaxSizeNow = MaxSize; element = NULL; }
    void Input();
    void display();                         //for debug
    ~SequenceList() { delete[] element; }
};


//this is test.cpp
#include <iostream>
#include <string.h>                                     
#include "test.h"
using namespace std;

template <typename T>
void SequenceList<T>::Input()                           //input the list
{
    element = new T[MaxSize];
    memset(element, 0, MaxSize);
    int i = 0;
    int x;
    cout << "input the length of the list:" << endl;
    cin >> x;
    cout << "input the list now" << endl;
    T temp;
    while (x--) {                                       
        cin >> temp;
        element[i] = temp;
        _size++;
        //if (_size++ > MaxSize) expand();
    }
    //MaxSizeNow = expand();
}

template <typename T>
void SequenceList<T>::display()                         //show the list
{
    for (int i = 0; i < _size; i++) {
        cout << element[i] << ends;
    }
    cout << endl;
}
frianH
  • 7,295
  • 6
  • 20
  • 45
  • 1
    Make sure you have implemented your template in a header. – drescherjm Oct 17 '19 at 03:17
  • Possible duplicate of [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – drescherjm Oct 17 '19 at 03:18

1 Answers1

0

Add this to the bottom of test.cpp

template void SequenceList<int>::display();
template void SequenceList<int>::Input();

Briefly, you will need to explicitly instantiate the templates for int because you didn't put the definitions in a header so the other translation unit knows not what those specific functions are. This is why you see lots of implementation in heavily templatized code.

rmccabe3701
  • 1,418
  • 13
  • 31