matt_rule
matt_rule

Reputation: 1400

Initialise template within derived constructor initialisation list

Foo inherits std::array<int, 2>. Is it possible to fill the array in the initialiser list of Foo's constructor?

If so what would be a valid alternative to the below syntax?

// Foo is always an array of 2 ints
struct Foo: std::array<int, 2>
{
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2> { x, y } {}
}

I tried adding an extra pair of braces, which works on g++, however not on the VC2015 compiler:

#include <array>
#include <iostream>

struct Foo : std::array<int, 2>
{
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
};

int main()
{
    Foo foo(5, 12);

    std::cout << foo[0] << std::endl;
    std::cout << foo[1] << std::endl;

    system("PAUSE");
}

and got the following errors: https://i.gyazo.com/4dcbb68d619085461ef814a01b8c7d02.png

Upvotes: 0

Views: 37

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

Yes you just need an extra pair of braces:

struct Foo: std::array<int, 2> {
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
                                                           ^        ^
};

Live Demo

For VC++ compiler you'll need a pair of parentheses instead of braces:

struct Foo : std::array<int, 2> {
    Foo() {}
    Foo(const int & x, const int & y) : std::array<int, 2>({ x, y }) {}
                                                          ^        ^
};

Upvotes: 2

Related Questions