【问题标题】:initializer list as argument to operator[]初始化器列表作为 operator[] 的参数
【发布时间】:2012-01-09 10:23:07
【问题描述】:

这个问题与here讨论的问题有关。

我尝试使用初始化列表来创建要传递给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"} ];
}

我的编译器 (GCC 4.6.1) 抱怨:

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

这应该是有效的 C++11 吗?

有趣的是,当使用 operator() 而不是 operator[] 时,它可以工作。

【问题讨论】:

  • 绝对是编译器错误,a.f({"aa", ""bb"})a[{"aa", ""bb"}] 之间应该绝对没有区别。
  • 传递一个临时显式编译,不过:a[ std::vector&lt;std::string&gt;({"hello", "world", "test"}) ];

标签: c++ c++11 curly-braces initializer-list


【解决方案1】:

是的,它是有效的 C++11,应该可以在任何兼容的编译器中工作。

请注意,gcc 对 C++11 的支持还很不成熟,此代码示例在任何 4.6 版本中都不会编译,而只能在 4.7 svn 快照版本中编译。

【讨论】:

  • 使用 svn trunk 修订版 179769 中的 GCC 4.7 也不起作用。与 GCC 4.6 相同的错误报告。
  • @MichelSteuwer:就在发布之前,我尝试使用本地构建的 gcc 4.7,即 r182904(我认为),并且成功了。
猜你喜欢
  • 2020-02-04
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 1970-01-01
相关资源
最近更新 更多