簡體   English   中英

為什么g++5在自動類型推導中推導對象而不是initializer_list

[英]Why does g++5 deduces object instead of initializer_list in auto type deduction

我最近遇到了這個代碼:

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<Foo> ,而g++5.1推導出為Foo AFAIK,類型確實應該是(確實違反直覺) std::initializer_list here 為什么 g++5 將類型推導出為Foo

有一個 C++1z 的提案,它為大括號初始化( N3922 )實現了新的類型推導規則,我猜 gcc 實現了它們:

對於直接列表初始化:
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 補丁

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM