c++ - expr[{ ... }] 有什么用?

标签 c++

This page在 cppreference 上说:

Built-in subscript operator
The subscript operator expressions have the form

expr1 [ expr2 ] (1)
expr1 [ { expr, ... } ] (2) (C++11)


2) The form with brace-enclosed list inside the square brackets is only used to call an overloaded operator[]


除此之外,没有示例或解释在 operator[] 中使用大括号意味着什么。
在 Godbolt.org 上,我证实了这一点,给出了 S s; , s[{3}]可以用来调用自定义S::operator[](int) , 而如果我们有 S s[5];然后 s[{3}]将无效。但是,它似乎不适用于多个参数,即 s[{3, 4}] (Clang 的错误提到参数被视为初始值设定项列表)。
那么……这个功能有什么意义呢?我什么时候想使用 [{}]而不是简单的[] ?

最佳答案

它的目的是允许从花括号初始化列表初始化任何参数类型。它被添加到 C++11 以配合新的初始化语法,其中允许大括号作为所有类型的初始化器(而不是仅用于聚合)。
一个例子

std::map<std::pair<int, int>, double> m {
 // content
};

// later

m[{1, 2}] = 2; // {1, 2} initializes a std::pair which is then used for sub-scripting.
{ ... }不是C++语法下的表达式,我们不能用{}生产中[ expr2 ] .需要一个明确的语法规则。

关于c++ - expr[{ ... }] 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62586825/

相关文章:

c++ - std::memory_order_relaxed 是否足以检查 "Availability"?

c++ - 如何在 C++ 中访问有关内存的元数据

C++ 类型 unsigned long int

c++ - 如何将 A*A std::array 拆分为 B*B block ?

c++ - 如何伪造键盘换档键。 Qt,Windows 10

c++ - 动态创建 std::vector//创建指向 vector 的指针

c# - 使用 c# 程序集的 c++ 项目 : how to speedup compile time?

c++ - 你能从 `volatile const char*` 构造一个字符串吗? (不使用 `const_cast` )

c++ - 最佳实践 : c++ header includes

c++ - 将类添加到基本 Qt GUI 应用程序时出现 Qt 链接器错误