简体   繁体   中英

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?

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

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;
};

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"...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM