加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

初始化 – 如何使用Uniform Initializers“减少创建C类型的类型

发布时间:2020-12-16 09:37:16 所属栏目:百科 来源:网络整理
导读:我用{}玩了很多新的统一初始化.像这样: vectorint x = {1,2,3,4};mapint,string getMap() { return { {1,"hello"},{2,"you"} };} 无可争议的是,这种初始化可能会改变我们的程序C. 但我想知道在Herb Sutter FAQs阅读Alfonses的问题时我是否错过了一些神奇的
我用{}玩了很多新的统一初始化.像这样:

vector<int> x = {1,2,3,4};
map<int,string> getMap() {
    return { {1,"hello"},{2,"you"} };
}

无可争议的是,这种初始化可能会改变我们的程序C.
但我想知道在Herb Sutter FAQs阅读Alfonses的问题时我是否错过了一些神奇的可能性.

Alfonse: Uniform initialization (the use of {} to call constructors when the type being constructed can be deduced) has the potential to radically reduce the quantity of typing necessary to create C++ types. It’s the kind of thing,like lambdas,that will change how people write C++ code. […]

有人能给我一个Alfonse在这里设想的例子吗?

解决方法

我认为他的意思是

std::vector<int> x{1,4};
std::map<int,std::string> y{{1,"you"}};

打字明显少于

std::vector<int> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
x.push_back(4);
std::map<int,std::string> y;
y.emplace(1,"hello");
y.emplace(2,"you");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读