user2771729
user2771729

Reputation: 458

Using templates as a function argument

I'm trying to convert my code to use templates so I can pass any type to it. I'm learning C++ from java so I'm not sure how to do it the c++ way. I'm getting an undeclared identifier error. Ill just show a small portion of the code. I want my function to accept any type of input. In Java I would just use generics.

class LList
{

private:

    template <typename T> struct ListItem
    {
        T item;
        ListItem* next;
    };

    int size;
    ListItem<int> *head;



public:

  void AddFront(ListItem<T> i) //This is the error
    {
        ListItem<T> *li = new ListItem<T>;
        li->item = i;
        li->next = head;
        head = li;
        ++size;
    }
}

Upvotes: 0

Views: 65

Answers (2)

James Adkison
James Adkison

Reputation: 9602

I believe the following edits fix your issue. Note: if this is just for learning so be it but otherwise you should probably be using standard containers (e.g., std::vector<T>, std::list<T>, etc).

template<typename T> // Added
class LList
{
private:
    struct ListItem
    {
        T item;
        ListItem* next;
    };

    int size; // This should probably be 'size_t'
    // ListItem<int> *head; // <- Why did you hard-code to 'int'?
    ListItem *head;

public:
    // void AddFront(ListItem<T> i) //This is the error
    void AddFront(T i)
    {
        ListItem *li = new ListItem;
        li->item = i;
        li->next = head;
        head = li;
        ++size;
    }
}

Upvotes: 1

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

Your class List doesn't have any template parameter and can only work with list items if type ListItem<int>, because that's what the head can point to. If you want a generic List, it has to be a template.

When you make List a template, things inside List should not be explicitly templates any more because they are implicitly templates, as members of a class template.

template <typename T> // <-- add
class LList
{

private:

    // template <typename T> <-- remove, not needed
    struct ListItem
    {
        T item;
        ListItem* next;
    };

    int size;
    ListItem *head; // <--- No <T>, no <int>



public:

  void AddFront(ListItem i) // <--- No <T>
    {
        ListItem *li = new ListItem; // <--- No <T>
        li->item = i;
        li->next = head;
        head = li;
        ++size;
    }
};

Note that your public AddFront takes a private ListItem argument. You will not be able to call it as is from the outside unless you get a ListItem object from somewhere.

Upvotes: 0

Related Questions