本文介绍了std :: make_pair中的c ++ 11 rvalue引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于C ++ 98

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

对于C ++ 11

template <class T1, class T2>
  pair<V1,V2> make_pair (T1&& x, T2&& y);  // see below for definition of V1 and V2
// make_pair example
#include <utility>      // std::pair
#include <iostream>     // std::cout
#include <functional>
#include <unordered_set>
using namespace std;

int main () {
  int i = 2;
  int j = 3;

  pair<int, int> p0 = make_pair<int, int>(2, 3); // fine
  pair<int, int> p1 = make_pair<int, int>(move(i), move(j)); // fine
  pair<int, int> p2 = make_pair<int, int>(i+0, j+0); // fine
  pair<int, int> p3 = pair<int, int>(i, j); // fine

  const int i2 = 2;
  const int j2 = 3;
  // error: no matching function for call to ‘make_pair(const int&, const int&)’
  pair<int, int> p4 = make_pair<int, int>(i2, j2); // wrong

  // error: no matching function for call to ‘make_pair(int&, int&)’
  pair<int, int> p5 = make_pair<int, int>(i, j); // wrong

  return 0;
}

问题>我发现用 make_pair 创建带有非右值引用变量的 pair 是不方便的.如您在上面的代码中看到的那样,以下行不会编译.

Question> I found that it is inconvenient to create a pair with non-rvalue reference variables by make_pair.As you can see above code, the following line doesn't compile.

  // error: no matching function for call to ‘make_pair(int&, int&)’
  pair<int, int> p4 = make_pair<int, int>(i, j); // wrong

在实践中,如何将 make_pair 与非右值引用变量一起使用?

In practice, how do you make use of make_pair with non-rvalue reference variables?

谢谢

推荐答案

std :: make_pair 的意义是为您推断参数的类型.否则,您可以这样写:

The point of std::make_pair is to deduce type of your arguments for you. Otherwise you could just write:

auto p = std::pair<int, double>(42, -1.5);

相反,您写

auto p = std::make_pair(42, -1.5);

这篇关于std :: make_pair中的c ++ 11 rvalue引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 21:53