Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make a classs istance variable take unlimited arguments in c++?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
        }
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading