本文介绍了为什么g++5在自动类型推导中推导对象而不是initializer_list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了这个代码:

I recently came upon this code:

struct Foo{};

int main()
{
    Foo a;
    // clang++ deduces std::initializer_list
    // g++5.1 deduces Foo
    auto b{a};
    a = b;
}

它用 g++5.1 编译得很好,但在 clang++ 中失败(同时使用 -std=c++11-std=c++14,相同结果).原因是 clang++ 将 b 的类型推导出为 std::initializer_list,而 g++5.1 推导出为 Foo.AFAIK,类型确实应该是(确实违反直觉)std::initializer_list 在这里.为什么 g++5 将类型推导出为 Foo?

It compiles fine with g++5.1, but fails in clang++ (used both -std=c++11 and -std=c++14, same results). The reason is that clang++ deduces the type of b as std::initializer_list<Foo>, whereas g++5.1 deduces as Foo. AFAIK, the type should indeed be (counter-intuitive indeed) std::initializer_list here. Why does g++5 deduces the type as Foo?

推荐答案

有一个 C++1z 的提案,它为大括号初始化实现了新的类型推导规则(N3922),我猜 gcc 实现了它们:

There is a proposal for C++1z that implements new type deduction rules for brace initialization (N3922), and I guess gcc implemented them:

对于直接列表初始化:
1.对于只有一个元素的braced-init-list,自动推导将从该条目中推导;
2. 对于一个多于一个元素的braced-init-list,自动推导将是格式错误的.

[示例:

auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
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<int>
auto x5{ 3 }; // decltype(x5) is int.

-- 结束示例]

这里是 gcc 补丁,关于"Unicorn 初始化."

Here is the gcc patch concerning the new changes with regards to "Unicorn initialization."

这篇关于为什么g++5在自动类型推导中推导对象而不是initializer_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 16:56