Mossid
Mossid

Reputation: 183

C++ get initializer list for constructor with other parameters

class V
{
private:
    int m_size;
    std::vector<int> m_list;
public:
    V(int size, std::initializer_list<int> init_list) : m_size(size)
    {
        m_list = std::vector<int>(init_list.begin(), init_list.end());
    }
};

I made a class which has a constructor taking multiple argument, including initializer_list. I want to use this class like

V v(2) = {1, 2};

but I'm only able to use this class like

V v(2, {1, 2});

Can't I separate arguments by non-initializer_list part and initializer_list part, like as first code I wrote?

Upvotes: 1

Views: 5030

Answers (1)

mty
mty

Reputation: 800

You can change your constructor to just get the initializer_list with:

class V
{
private:
    std::vector<int> m_list;
    int m_size;
public:
    V(std::initializer_list<int> init_list):
        m_list(init_list.begin(), init_list.end()),
        m_size(m_list.size()) { }
};

and construct V objects with:

V v1 = {1,2};
V v2({1, 2});

You don't need the size to be input anymore thanks to std::vector.

Upvotes: 2

Related Questions