0

The goal of the program is to use templates to create generic lists. My DoublyLinkedList.cpp file takes in a generic type and later stores elements in a linked-list fashion. Anyways, I'm having trouble getting my main function to initialize the list. Some of my code can be found below.

int main(int argv, char* argv[])
{
    cout << "Enter list type (i = int, f = float, s = std:string)";
    char listType;
    cin >> listType;

    if (listType == 'i')
    {
        DoublyLinkedList<int>* list = new DoublyLinkedList<int>();
    }
    else if (listType == 'f')
    {
        DoublyLinkedList<float>* list = new DoublyLinkedList<float>();
    }
    else 
    {
        DoublyLinkedList<string>* list = new DoublyLinkedList<string>();
    }

    (*list).print();
}
  • If DoublyLinkedList is a template, then it [generally needs to go into a header, not a separate cpp file](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file). – nanofarad Oct 12 '21 at 20:08
  • 1
    Note: `DoublyLinkedList` and its friends are all scoped by the respective `if` statements they are defined in. `(*list).print();` is not possible because `list` is out of scope and no longer exists. You have to get significantly sneakier to get the behaviour you want. So much sneakier that you might be better off describing your desired endgame fully so we can offer alternatives. – user4581301 Oct 12 '21 at 20:13

1 Answers1

0

Since this site is useless and unhelpful I just figured it out myself. The best way I found to accomplish this was to create a function in main.cpp that takes in a template and implements all functions using the object there.

void testList(DoublyLinkedList<T>* list)
{
    (*list).print();
}

int main(int argv, char* argv[])
{
    cout << "Enter list type (i = int, f = float, s = std:string)";
    char listType;
    cin >> listType;

    if (listType == 'i')
    {
        DoublyLinkedList<int>* list = new DoublyLinkedList<int>();
        testList(list);
    }
    else if (listType == 'f')
    {
        DoublyLinkedList<float>* list = new DoublyLinkedList<float>();
        testList(list);
    }
    else 
    {
        DoublyLinkedList<string>* list = new DoublyLinkedList<string>();
        testList(list);
    }
}