开发者

std::make_pair vs C++11 uniform initializer

Is there a drawback to using the latter? Is std::make_pair more v开发者_StackOverflow中文版ersatile/compatible or are they truly interchangeable?

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.

(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.

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. If you haven't, then make_pair might be a good thing. If you have types A and B, 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 use std::make_pair, which will properly decay the type of the expressions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜