C++ 为什么g++;5在自动类型推断中推断对象而不是初始值设定项\u列表
我最近发现了以下代码:C++ 为什么g++;5在自动类型推断中推断对象而不是初始值设定项\u列表,c++,c++11,auto,clang++,gcc5,C++,C++11,Auto,Clang++,Gcc5,我最近发现了以下代码: 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,结果相同)。原因是,然而AFAIK,类型确实应该是(与直觉相反)std::initiali
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
,结果相同)。原因是,然而AFAIK,类型确实应该是(与直觉相反)std::initializer\u list
此处。为什么g++5将类型推断为Foo
有一个针对C++1z的建议,它为大括号初始化()实现了新的类型推断规则,我猜gcc实现了这些规则:
对于直接列表初始化:1.对于只有一个元素的带括号的init列表,自动推断将从该条目中推断出来
2.对于包含多个元素的大括号init列表,自动推断的格式将不正确 [示例:
auto-x1={1,2};//decltype(x1)是std::initializer\u list
auto x2={1,2.0};//错误:无法推断元素类型
auto x3{1,2};//错误:不是单个元素
auto x4={3};//decltype(x4)是std::initializer\u list
auto x5{3};//decltype(x5)是int。
--[结束示例]
以下是关于“Unicorn初始化”的新更改。您使用的编译器标志是什么?@juanchopanza我尝试了
-std=c++11
和-std=c++14
在这种情况下,这是一个编译器错误。无论如何,您应该把这类信息放在问题中。这有点迷惑了答案。看。特别地,“EWG的方向是我们认为这是C++ 14中的缺陷。”LOL@“独角兽初始化”。比“制服”好多了。
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.