gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:04:20 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com