TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

std::make_pair

参考

What is the purpose of std::make_pair vs the constructor of std::pair?
Ask

std::make_pair

为什么不从构造函数推断模板参数?

类模板的模板参数推导(修订版5)

正文

c++98

1
2
3
4
5
6
7
8
template <class T1, class T2>
pair<T1,T2> make_pair (T1 x, T2 y);

template <class T1,class T2>
pair<T1,T2> make_pair (T1 x, T2 y)
{
return ( pair<T1,T2>(x,y) );
}

c++11

1
2
3
4
5
6
7
8
9
10
11
template <class T1, class T2>
pair<V1,V2> make_pair (T1&& x, T2&& y); // see below for definition of V1 and V2

The function returns:

pair<V1,V2>(std::forward<T1>(x),std::forward<T2>(y))

Where the types V1 and V2 are the decay(衰变) equivalents(等价物) of T1 and T2, respectively(分别) (except for reference_wrapper types, for which the corresponding reference type is used instead).

If T1 and/or T2 are rvalue references, the objects are moved and x and/or y are left in an undefined but valid state.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// make_pair example
#include <utility> // std::pair
#include <iostream> // std::cout

int main () {
std::pair <int,int> foo;
std::pair <int,int> bar;

foo = std::make_pair (10,20);
// ok: implicit conversion from pair<double,char>
bar = std::make_pair (10.5,'A');

std::cout << "foo: " << foo.first << ", " << foo.second << '\n';
std::cout << "bar: " << bar.first << ", " << bar.second << '\n';

return 0;
}
foo: 10, 20
bar: 10, 65

总结

模板类的构造函数在c++17前是不能自动推导参数类型的,所以需要手动指定类型:

std::pair <int,int> p(1,2);

而c++17后可以直接:

std::pair p(1, 'a');

具体原因我也不是很懂,可以看参考的文章。但是普通函数是支持类型推导的,所以之前c++17以前实现了make_pair:

template <class T1,class T2>
pair<T1,T2> make_pair (T1 x, T2 y)
{
  return ( pair<T1,T2>(x,y) );
}

这样写起来就不那么繁琐了:

1
2
3
4
5
MyClass o1;
MyClass o2;
auto p = std::make_pair(o1, o2);

auto pp = std::pair<MyClass, MyClass> { o1, o2 };

应该是编译器会根据实际的类型去生成一个一个make_pair匹配的实现函数,转换成pare<>的格式。

ending

81261415_p0_master1200.jpg

----------- ending -----------