user1899020
user1899020

Reputation: 13575

How to make an array's derived type accept aggregate initialization?

For example

class A : public std::array<int, 3>
{
};

And

A a{1, 2, 3}; // failed currently.

How to make an array's derived type accept aggregate initialization?

Upvotes: 4

Views: 200

Answers (3)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42889

You could provide a variadic template constructor as follows:

class A : public std::array<int, 3> {
public:
  template<typename... Args> constexpr A(Args&& ...args) 
    : std::array<int, 3>{{std::forward<Args>(args)...}} {}
};

Live Demo

Edit:

The following version works also on Visual Studio:

class A : public std::array<int, 3> {
public:
    template<typename... Args> constexpr A(Args&& ...args) 
      : std::array<int, 3>(std::array<int,3>{std::forward<Args>(args)...}) {}
};

Live Demo

Upvotes: 7

PcAF
PcAF

Reputation: 2007

EDIT: As others pointed out in comments, this won't work for std::array because std::array doesn't contain constructor taking initializer_list. But it might be useful for other containers that have constructor taking initializer_list, for example std::vector.

You can use inheriting constructor(since C++11):

class A: public std::vector<int,3>
{
      using std::vector<int,3>::vector;
};

Upvotes: 1

Boiethios
Boiethios

Reputation: 42739

Just define a constructor like that:

A(std::array<int, 3>);

example:

#include <array>
#include <iostream>

struct A : public std::array<int, 3>
{
    A(std::array<int, 3>    a) :
        std::array<int, 3>{a}
    {
    }
};

int main(void)
{
    A   a({1, 2, 3});

    std::cout << a[0] << "\n";
    std::cout << a[1] << "\n";
    std::cout << a[2] << "\n";
}

That is not an aggregate initialization, but it is an "as if"...

Upvotes: 0

Related Questions