微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我用{}玩了很多新的统一初始化.像这样:

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");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐