c++, how to make a template function call without a type definition

Asked 1 years ago, Updated 1 years ago, 65 views

Implementing a double linked list that can have different types of variables in one list.

Example) 11 <-> "aa" <-> 'A' <-> 1.2345

I'm trying to return the value stored in the nth of the list through the get(intn) function without defining the type of the function in the main, but it didn't work out well, so I'm posting to ask for your help ㅠ<

.hpp file

class node_base{
    public:
        node_base *next;
        node_base *prev;
        node_base () { next = 0; prev = 0; }
        virtual void print () = 0;
        virtual int get_node_size () = 0;
};

template <typename T>
class node : public node_base{
    public:
        T data;
        node (const T& val) : data(val) {}
        virtual void print (){ cout << data << " "; }
        virtual int get_node_size () { return sizeof (data); }
        T getData () { return data; }
};

class unvlist{
        node_base *head;
    public:
        int len;
        unvlist ();
        void print () {
            node_base *h = head;
            while (h->next != NULL){
                h->print ();
                h = h->next;
            }
            h->print ();
        }
        template <typename T> unvlist (const T* arr, int n);
        ~unvlist ();
        //operator +
        //operator ==
        template <typename T> void set (int n, const T& val);
        template <typename T> T get (int n);
        template <typename T> T insert (int n, const T& val);
        void erase (int n);
        int size ();
        void pop_back ();
        void pop_front ();
        template <typename T> void push_back (const T& val);
        template <typename T> void push_front (const T& val);
};
/* get function: Returns the value stored in the nth in the list. */
template <typename T>
T unvlist :: get (int n){
    T retval;

    if (n >= len || n < 0){
        cout << "'In unvlist::get'-> Out of Bound!!!" << endl;
        return 0;
    }
    if (n >= 0){
        node_base *h = head;
        for (int i = 0; i < n; i++) { h = h->next; }
        retval = static_cast<node<T>*>(h)->getData ();
    }
    return retval;
}

main.cpp file

int main(){
    unvlist *l1 = new unvlist ();

    l1->push_back<string> ("aa");
    l1->push_back<char> ('A');
    l1->push_back<float> (1.2345);
    l1->push_front<int> (11);

    for (int i = 0; i < 4; i++){
        output all values in cout <<<l1->get(i) <<"; // list
    }   }   cout << endl;

    return 0;
}

compile error compile error

c++ template

2022-09-22 12:29

1 Answers

 template <typename T> T get (int n);

Instead, the return type is implemented as a node, and

node get(int n);

How about overriding operator << in node (or node_base)?


2022-09-22 12:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.