C ++ 11 / C ++ 14中的自动和大括号初始化[重复](auto and brace initialization in C++11/C++14 [duplicate])

编程入门 行业动态 更新时间:2024-10-28 19:35:02
C ++ 11 / C ++ 14中的自动和大括号初始化[重复](auto and brace initialization in C++11/C++14 [duplicate])

这个问题在这里已有答案:

表达式的不同编译器行为:auto p {make_pointer()}; 1个答案

当我用clang和gcc编译下面的代码时, T的推导方式不同。

#include<initializer_list> //for clang //to see how T is deduced(form compiler error). template<typename T> void foo(T); int main() { auto var1{2}; foo(var1); }

这是我得到的。

clang 3.6(c++11/c++14) gcc 4.9(c++11/c++14) T = std::initializer_list<int> gcc 5.1(c++11/c++14) T = int

我认为T应该是std::initializer_list<int> 。

为什么在gcc 5.1中T = int ?

This question already has an answer here:

Different compiler behavior for expression: auto p {make_pointer()}; 1 answer

When I compile the below code with clang and gcc T is deduced differently.

#include<initializer_list> //for clang //to see how T is deduced(form compiler error). template<typename T> void foo(T); int main() { auto var1{2}; foo(var1); }

Here is what I got.

clang 3.6(c++11/c++14) gcc 4.9(c++11/c++14) T = std::initializer_list<int> gcc 5.1(c++11/c++14) T = int

I think T should be std::initializer_list<int>.

Why is T = int in gcc 5.1?

最满意答案

这是对C ++ 17规范的改进建议 - N3922 (我不确定它是否已被接受)。

基本上来自Scott Meyers的演示文稿 ,幻灯片20涵盖了新规则。

auto var1 {2} ;

这里, var1将被推断为int 。

看起来好像有些编译器已经实现了这一改变。 我相信这种变化更“直观”,但你的里程可能会有所不同。 我认为在这个临时阶段,更喜欢=初始化,它可能更便携。

这里的答案更详细地说明了提案的历史和提出的缺陷。

This is proposed change to the C++17 specification - N3922 (I'm not sure if it has been accepted yet).

Basically this presentation from Scott Meyers, slide 20 covers the new rules.

auto var1 {2} ;

Here, var1 will be deduced to be an int.

It does look like some compilers have already implemented the change. I believe the change is more "intuitive" but your mileage may vary. I think in this interim phase, prefer the = initialisation, it may be more portable.

The answer here has some more detail on the history of the proposals and defects raised.

更多推荐

本文发布于:2023-04-27 13:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327097.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:括号   初始化   duplicate   initialization   brace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!