Home > OS >  Undeclared Idenfitier - Templates C
Undeclared Idenfitier - Templates C

Time:10-20

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();
}

CodePudding user response:

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);
    }
}
  • Related