bitmask
bitmask

Reputation: 34628

Why do I need a compound literal like temporary construction to initialise my std::array member?

Consider this minimal example:

#include <array>
struct X {
  std::array<int,2> a;
  X(int i, int j) : a(std::array<int,2>{{i,j}}) {}
  //                 ^^^^^^^^^^^^^^^^^^       ^
};

According to other posts I shouldn't have to explicitly construct a temporary in this situation. I should be able to write:

  X(int i, int j) : a{{i,j}} {}

but this and several other (similar) versions I tried are all refused by my (admittedly quite old) g++ 4.5.2. I currently have only that one for experimentation. It says:

error: could not convert ‘{{i, j}}’ to ‘std::array<int, 2ul>’

Is this a limitation of this compiler implementation or what's going on?

Upvotes: 0

Views: 331

Answers (1)

Xeo
Xeo

Reputation: 131789

The problem is, as a lot of times, the compiler version. The following code works fine with GCC 4.7.1:

#include <array>

struct X{
  std::array<int, 2> a;
  X() : a{{1,2}} {}
};

int main(){
  X x;
}

Live example.

Upvotes: 6

Related Questions