gpt4 book ai didi

c++ - 返回并自动推导 std::initializer_list

转载 作者:可可西里 更新时间:2023-11-01 16:38:15 26 4
gpt4 key购买 nike

在以下内容中:

auto x = {0}; // auto deduction of std::initializer_list<int>
auto y = []() -> std::initializer_list<int> { return {0}; }(); //explicit
auto z = []() { return {0}; }(); // won't compile

为什么不能返回并自动推断 std::initializer_list 的类型?

最佳答案

好吧,因为标准是这么说的,而且因为 braced-init-list 不是表达式。根据 C++11 标准的第 5.1.2/4 段:

[...] If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type:

— if the compound-statement is of the form

{ attribute-specifier-seq(opt) return expression ; }

the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);

— otherwise, void.

上面清楚地表明,当且仅当 return 语句后跟一个 表达式时,返回类型将被推断为除 void 之外的任何其他类型braced-init-list 本身并不是一个表达式——它没有类型,也没有产生值。它只是一种可以在初始化上下文中使用的语言结构。

上面的段落还提供了一个例子:

[ Example:

auto x1 = [](int i){ return i; }; // OK: return type is int
auto x2 = []{ return { 1, 2 }; }; // error: the return type is void (a
// braced-init-list is not an expression)

end example ]

最后,如果问题是:

为什么引入了一个特殊规则来推导从花括号初始化列表初始化的auto 变量的类型,而类似的规则不是return 后跟一个 braced-init-list 时,引入用于推导 lambda 的返回类型?

那么这个问题就没有建设性。另请注意,模板的类型推导也不适用于braced-init-lists:

template<typename T>
void foo(T);

foo({1, 2}); // ERROR! T is NOT deduced to be std::initializer_list<int>

关于c++ - 返回并自动推导 std::initializer_list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17384193/

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