考虑下面的程序:为什么这个变量不是在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:
For a braced-init-list with only a single element, auto deduction will deduce from that entry;
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
?
@Columbo:为什么它在C++ 14中编译得很好。你不觉得它不应该编译? – Destructor
请参阅[表达式的不同编译器行为:auto p {make_pointer()};](http://stackoverflow.com/q/31301369/1708801),不清楚那里提到的提案是否应用于C++ 14或者没有,与此有冲突的信息。这里也存在实施差异。 –
@ShafikYaghmour它看起来像[Clang开发者打算(最终)追溯应用这种变化](http://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20150209/123102.html) 。 –