0

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?

Community
  • 1
  • 1
bitmask
  • 32,434
  • 14
  • 99
  • 159
  • 2
    That's not a compound literal; C++ doesn't even have them! – eq- Sep 06 '12 at 21:06
  • 4
    Yes, your outdated GCC is the issue -- [works fine with 4.7.1](http://liveworkspace.org/code/af413b3d9b062ea32cd3dd7b3e3aff33). – ildjarn Sep 06 '12 at 21:08
  • I'd assumed he was talking about multicharacter literals, but there's none of those in this question either. – Mooing Duck Sep 06 '12 at 21:09
  • Yep, that's why C++ syntax and semantics are driving me nuts. Agreed to Mr Torvalds. –  Sep 06 '12 at 21:09
  • @eq-: It's not? Then it's a proper constructor? What do we call this, then. It is the default constructor to a temporary; Maybe there's a name for it. – bitmask Sep 06 '12 at 21:09
  • @bitmask, it's a simple object construction (using the new C++11 brace syntax, combined with initializer lists). Can't remember any special name for it. – eq- Sep 06 '12 at 21:12
  • @eq-: I changed the title. Hope this is better. – bitmask Sep 06 '12 at 21:13

1 Answers1

6

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.

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • This was answered in the comments by ildjam. – Matt Phillips Sep 06 '12 at 21:57
  • 5
    @MattPhillips: Okay, and because I wrote my answer at the same time, I get a downvote? Sorry that I was a little bit slower with typing. Also, a question needs an answer to accept, not just a comment. – Xeo Sep 06 '12 at 22:00
  • Just got to your comment now, sorry about that Xeo. I should have looked at the timestamps and now my downvote is locked. FWIW I made it up to you elsewhere. :) – Matt Phillips Sep 07 '12 at 00:35
  • 1
    @MattPhillips: You can make a stealth edit (as I just did, just removing / adding some whitespace) to make it unlocked again, for future reference. :) – Xeo Sep 07 '12 at 04:40