std::make_pair 与 C++11 统一初始值设定项
使用后者有缺点吗? std::make_pair
是否更通用/兼容,或者它们真的可以互换吗?
谢谢!
Is there a drawback to using the latter? Is std::make_pair
more versatile/compatible or are they truly interchangeable?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它们有何关系?使用初始值设定项列表构造函数不适用于对,因为
pair
是异构类型的,而初始值设定项列表构造函数使用initializer_list
,它只能使用检索同构类型的初始值设定项列表。(查看规范,它实际上应该被称为“初始化器列表构造函数”,而不是“初始化器列表构造函数”。您真的是指第一个吗?如果不是,您指的是什么呢?)。
如果您只是参考使用初始化列表来初始化
std::pair<>
,而不是使用std::make_pair
和使用auto
,我认为两者都很好。如果您已经拥有类型
A
和B
并且可以将它们用于pair
,那么初始化器列表是一个很好的使用方法。如果还没有,那么make_pair
可能是一件好事。如果您有类型A
和B
,但不确定它们是否已正确转换(即它们不应该是数组或函数类型,并且您可能还需要它们为非引用类型),那么使用 std::make_pair 可能会更容易,它会正确地衰减表达式的类型。How are they related? Using an initializer list constructor doesn't work for a pair, because a
pair
is heterogeneously typed, while an initializer list constructor uses aninitializer_list<T>
, which is only usable to retrieve an homogeneously typed initializer list.(Looking into the spec, it should really be called "initializer-list constructor", instead of "initializer list constructor". Do you really mean to refer to the first? If not, what do you refer to?).
If you just refer to initialize a
std::pair<>
using an initializer list against usingstd::make_pair
and usingauto
, I think both are fine.If you have already the types
A
andB
and can use them for thepair
, then the initializer list is a good way to use. If you haven't, thenmake_pair
might be a good thing. If you have typesA
andB
, but aren't sure whether they are already transformed properly (i.e they should not be array or function types, and you probably also want them to be non-reference types), then it might be easier to usestd::make_pair
, which will properly decay the type of the expressions.