为什么这个变量不是在C ++ 14中的g ++中推演为initializer_list? [英] why this variable isn't deduced as initializer_list in g++ in C++14?

查看:307
本文介绍了为什么这个变量不是在C ++ 14中的g ++中推演为initializer_list?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序:

  #include< iostream> 
int main()
{
int n = 3;
int fact = 1;
for(auto i {1}; i <= n; i ++)
fact * = i;
std :: cout<<fact of<< n<<is<
}

即使使用 std = c ++ 14 选项。请观看实时演示此处。但是在C ++ 14中,变量 i 应该根据 initializer_list /stackoverflow.com/questions/30007692/why-does-g5-deduces-object-instead-of-initializer-list-in-auto-type-deduction\"> this



有一个C ++ 1z的建议,它为大括号初始化实现了新的类型扣除规则:


list-initialization:


  1. 对于只有一个元素的支撑初始化列表,自动扣除将从该条目中推导出;


  2. 对于带有多个元素的支撑初始化列表,自动扣除将不合格。


[示例:



auto x1 = {1 ,2}; // decltype(x1)is std :: initializer_list



auto x2 = {1,2.0}; //错误:无法推导元素类型



auto x3 {1,2}; //错误:不是单个元素



auto x4 = {3}; // decltype(x4)is std :: initializer_list



auto x5 {3}; // decltype(x5)是int。



- end example]


++ 17。因此,当我使用 -std = c ++ 14 时,程序不应该编译。这是g ++中的错误吗?在C ++ 14中不应该变量 i 推导为 initializer_list


有一个C ++ 1z的建议,它为大括号初始化实现了新的类型推导规则。


不完全是。如果你按照实际文件的链接,它是:


EWG的方向是我们认为这是C ++ 14中的缺陷。


这是足够让实现者也把它当作一个缺陷,因此改变编译器的行为,即使在C ++ 14模式。


Consider the following program:

#include <iostream>
int main()
{
    int n = 3;
    int fact = 1;
    for(auto i{1};i<=n;i++)
        fact*=i;
    std::cout<<"fact of "<<n<<" is "<<fact;
}

It compiles fine on ideone even when I use -std=c++14 option. See live demo here. But in C++14 the variable i should be deduced as initializer_list according to this.

There is a proposal for C++1z that implements new type deduction rules for brace initialization:

For direct list-initialization:

  1. For a braced-init-list with only a single element, auto deduction will deduce from that entry;

  2. For a braced-init-list with more than one element, auto deduction will be ill-formed.

[Example:

auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list

auto x2 = { 1, 2.0 }; // error: cannot deduce element type

auto x3{ 1, 2 }; // error: not a single element

auto x4 = { 3 }; // decltype(x4) is std::initializer_list

auto x5{ 3 }; // decltype(x5) is int.

-- end example]

So, the rules changed in C++17. As such, the program shouldn't compile when I use -std=c++14. Is this bug in g++? Shouldn't the variable i deduced as initializer_list in C++14?

解决方案

There is a proposal for C++1z that implements new type deduction rules for brace initialization

Not exactly. If you follow the link to the actual paper, it reads:

Direction from EWG is that we consider this a defect in C++14.

Which is enough to get implementors to also treat it as a defect, and hence change the compiler behaviour even in C++14 mode.

这篇关于为什么这个变量不是在C ++ 14中的g ++中推演为initializer_list?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆