简体   繁体   English

std::make_pair 与 C++11 统一初始值设定项

[英]std::make_pair vs C++11 uniform initializer

Is there a drawback to using the latter?使用后者有什么缺点吗? Is std::make_pair more versatile/compatible or are they truly interchangeable? std::make_pair更通用/兼容还是它们真的可以互换?

Thanks!谢谢!

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 an initializer_list<T> , which is only usable to retrieve an homogeneously typed initializer list.使用初始化列表构造函数对配对不起作用,因为pair是异构类型的,而初始化列表构造函数使用initializer_list<T> ,它只能用于检索同构类型的初始化列表。

(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 using std::make_pair and using auto , I think both are fine.如果您只是参考使用初始化列表初始化std::pair<>不是使用std::make_pair和使用auto ,我认为两者都很好。

auto p = std::make_pair(a, b);
std::pair<A, B> p{a, b};

If you have already the types A and B and can use them for the pair , then the initializer list is a good way to use.如果您已经拥有AB类型并且可以将它们用于pair ,那么初始化列表是一个很好的使用方式。 If you haven't, then make_pair might be a good thing.如果你还没有,那么make_pair可能是一件好事。 If you have types A and B , but aren't sure whether they are already transformed properly (ie 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 use std::make_pair , which will properly decay the type of the expressions.如果您有类型AB ,但不确定它们是否已经正确转换(即它们不应该是数组或函数类型,并且您可能还希望它们是非引用类型),那么可能更容易使用std::make_pair ,它将正确地衰减表达式的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM