initializer list as argument to operator[]
Asked Answered
S

2

7

This question is related to the one discussed here.

I try to use an initializer list to create an argument to be passed to operator[].

#include <string>
#include <vector>

struct A {

std::string& operator[](std::vector<std::string> vec)
{
  return vec.front();
}

};

int main()
{
    // ok
    std::vector<std::string> vec {"hello", "world", "test"};

    A a;
    // error: could not convert '{"hello", "world", "test"}' to 'std::vector...'
    a[ {"hello", "world", "test"} ];
}

My Compiler (GCC 4.6.1) complains:

g++ -std=c++0x test.cpp
test.cpp: In function ‘int main()’:
test.cpp:20:8: error: expected primary-expression before ‘{’ token
test.cpp:20:8: error: expected ‘]’ before ‘{’ token
test.cpp:20:8: error: expected ‘;’ before ‘{’ token
test.cpp:20:35: error: expected primary-expression before ‘]’ token
test.cpp:20:35: error: expected ‘;’ before ‘]’ token

Should this be valid C++11?

Interestingly, when using operator() instead of operator[] it works.

Sou answered 9/1, 2012 at 10:23 Comment(2)
Most definitely, it is compiler bug, as there should be absolutely no difference between a.f({"aa", ""bb"}) and a[{"aa", ""bb"}].Sanity
Passing a temporary explicitly compiles, though: a[ std::vector<std::string>({"hello", "world", "test"}) ];Bestial
E
4

Yes, it is valid C++11 and should work in any compliant compiler.

Please note that C++11 support in gcc is quite immature, and this code example will not compile in any 4.6 version, but only in 4.7 svn snapshot versions.

Emmott answered 9/1, 2012 at 10:49 Comment(2)
Using GCC 4.7 from svn trunk revision 179769 doesn't work either. Same error report as with GCC 4.6.Sou
@MichelSteuwer: Right before posting this I tried with my local build of gcc 4.7 which is r182904 (I think), and it worked.Emmott
O
0

Yes, it is valid. The version of GCC you're using doesn't have full support for C++11 yet, so it fails to compile, even when it's standard-compliant.

A more recent version of GCC compiles your code. See live example at Compiler Explorer.

Ophiology answered 3/9, 2023 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.