6

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.

Community
  • 1
  • 1
Michel
  • 61
  • 2
  • 1
    Most definitely, it is compiler bug, as there should be absolutely no difference between `a.f({"aa", ""bb"})` and `a[{"aa", ""bb"}]`. – Nawaz Jan 09 '12 at 10:50
  • Passing a temporary explicitly compiles, though: `a[ std::vector({"hello", "world", "test"}) ];` – jrok Jan 09 '12 at 11:43

1 Answers1

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.

PlasmaHH
  • 15,673
  • 5
  • 44
  • 57
  • Using GCC 4.7 from svn trunk revision 179769 doesn't work either. Same error report as with GCC 4.6. – Michel Jan 09 '12 at 12:01
  • @MichelSteuwer: Right before posting this I tried with my local build of gcc 4.7 which is r182904 (I think), and it worked. – PlasmaHH Jan 09 '12 at 12:33