Breon Thibodeaux
Breon Thibodeaux

Reputation: 93

How can my List class contain all types?

This question is part of assignment for my data structures class I'll post part of the description below.

Modify your List class (with the linked list as backend) to support generics so that it not only can contain integers, but other types such as floats and characters. I have provided a new main function as well as the output generated from my implementation. Hint: you only need to add one line and change a single word in five lines. So this should not take you long.

The problem i'm having is, is understanding the question while it may seem pretty simple to most i might just be over thinking it. It states i only need to add one line and i'm assuming that line would be inserted in the portion of the following code:

class List
{
  private:
    struct Node
    {
        int data;
        Node *link;
    };

Now i'm unsure of how i'll add this last line but i was thinking maybe i could do:

int, char, float data;

or is that not a valid way of doing so? i'm aware of the 5 places elsewhere in the code i'd need to change things but the question is very confusing to me. Thank you.

Upvotes: 3

Views: 121

Answers (2)

Jörg Beyer
Jörg Beyer

Reputation: 3671

unions combine different data types in one location.

e.g.

union combined_data {
int i;
float f;
};

you can either say combined_data.i = 42;

or combined_data.f = 3.14;

A different solution is to use templates. That is: make several classes, out of one definition. They are different in (for example) a type.

template<T>
class List
{
private:
    struct Node
    {
        T data;
        Node *link;
    };
};

you can use it as

List<int> intlist;

or

List<float> floatlist;

Upvotes: 1

Enrico Granata
Enrico Granata

Reputation: 3339

would

template <typename T>
class List {
  private:
   struct Node {
    T data;
    Node *link;
   }
}

work?

Upvotes: 6

Related Questions