Home > Mobile >  How do I make a classs istance variable take unlimited arguments in c ?
How do I make a classs istance variable take unlimited arguments in c ?

Time:12-09

I am recreating a class list data structure in c with every feature that comes to mind, for educational purposes. I was wondering if there was a way to allow the user to use this sintax:

list my_list = {1, 2, 3, 4, 5};

or even this sintax if possible (I don't think it is but I'll ask anyways)...

list my_list = [1, 2, 3, 4, 5];

Let me know if the only way to do this is to mess with the compiler and it can't be done with operator overloading.

CodePudding user response:

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 (auto x : l) {
            // do something with x
        }
    }
};
  • Related