2015-11-03 62 views
-1

考虑下面的程序:为什么这个变量不是在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 "<<fact; 
} 

它编译于ideone罚款,甚至当我使用-std=c++14选项。查看现场演示here。但是在C++ 14中,变量i应根据this推导为initializer_list

没有为C++ 1Z的建议实现捆带初始化新类型推演规则:

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]

所以,规则改变了C++ 17。因此,当我使用-std=c++14时,程序不应该编译。 g ++中有这个bug吗?在C++ 14中,变量i不应该推导为initializer_list

+0

@Columbo:为什么它在C++ 14中编译得很好。你不觉得它不应该编译? – Destructor

+0

请参阅[表达式的不同编译器行为:auto p {make_pointer()};](http://stackoverflow.com/q/31301369/1708801),不清楚那里提到的提案是否应用于C++ 14或者没有,与此有冲突的信息。这里也存在实施差异。 –

+0

@ShafikYaghmour它看起来像[Clang开发者打算(最终)追溯应用这种变化](http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20150209/123102.html) 。 –

回答

4

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

不完全是。如果按照链接到实际的纸张,有这么一句话:

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

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

+0

所以g ++。g ++中没有错误 – Destructor

+1

你可以说一个实现不应该把它当作一个C++ 14的缺陷,直到有一个官方的DR,但我不会被这样的论证所证实,我认为GCC的行为至少是没有错误 – hvd

+0

如果你不把这些事情扼杀在萌芽状态,一致性的最后边缘可能会略微失控,我想起了web浏览器合规性的噩梦:“微软说,Acid3不同意以[IE8]为目标,而IE8只会改进一些标准......得分20/100,这比所有相关的竞争者都差得多......“恕我直言,海湾合作委员会可以独家*脚趾,如果这是什么它需要保持这种分歧。 –

相关问题