1

I am reimplementing std::list for educational purposes.

I was wondering if there was a way to allow the user to use this syntax for initialization:

my::list l = {1, 2, 3, 4, 5};
ugo_capeto
  • 129
  • 8

2 Answers2

5

This is what initializer lists are for. You could for example have a constructor like this:

class list {
public:
    list(std::initializer_list<int> l) {
        for (int x : l) {
            // do something with x
        }
    }
};

Or making it more generic by using templates:

template<typename T>
class list {
public:
    list(std::initializer_list<T> l) {
        for (const auto &x : l) {
            // do something with x
        }
    }
};
kessler bebe
  • 106
  • 5
0

This is my solution using variadic templates:

template<typename T>
class my::list {
public:
    template<typename... Args>
    list(Args... args) { init(args...); }
    void push_back(T);
private:
    template<typename... Args>
    void init(T value, Args... args) {
        push_back(value);
        init(args...);
    }
};

the init function calls itself recursively, and it checks that the first value is of type T, then pushes it inside the list.

ugo_capeto
  • 129
  • 8