栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++17 关键新特性介绍及代码讲解 (2) --- New auto rules for direct-list-initialization

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++17 关键新特性介绍及代码讲解 (2) --- New auto rules for direct-list-initialization

C++17 关键新特性介绍及代码讲解 (2) — New auto rules for direct-list-initialization

一句话概括:

对于使用 brace-list ( 即花括弧 { }) 进行初始化的 auto变量,更新了 auto变量类型的推导规则,更新后的规则更加清晰。

更新后的规则如下:

  • copy-initialization 的情况:
    { }里的变量类型需要完全一致, 此时 auto推导为 std::initializer_list类型;其他情况为语法错误。
auto x1 = { 1, 2 };   // decltype(x1) is std::initializer_list
auto x2 = {'c'};      // decltype(x1) is std::initializer_list
// error
auto x3 = { 1, 2.0 }; // error: element types not identical.
  • direct-initialization 的情况:
    如果 { }里只有单个元素, 则 auto变量类型推导为该元素类型 , 如int、double等。
    如果 { }里有多个元素, 则为语法错误。
auto x4{ 1 }; // decltype(x4) is int
auto x5{ x1 }; // decltype(x5) is std::initializer_list
// error
auto x6{1, 2}; // error: multiple elements.

完整 demo 代码参见 gitee.com 上的公开代码仓库 : [auto_bound_list_initialization]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971809.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号