【问题标题】:std::pair substitution failed with std::size_tstd::pair 替换因 std::size_t 失败
【发布时间】:2021-09-15 00:35:26
【问题描述】:
#include <utility>
#include <vector>

using namespace std;

std::pair<std::size_t, std::size_t> func(const std::vector<int>& numbers, int target) {
    for(std::size_t i =0; i < numbers.size(); i++)
    {   
      for(std::size_t j = i; j < numbers.size(); j++)
      {   
        if(numbers[i] + numbers[j] == target)
          return std::make_pair<std::size_t, std::size_t>(i,j);
      }   
    }   
    return std::make_pair<std::size_t, std::size_t>(0,0);
}

错误:

test.cpp: In function ‘std::pair<long unsigned int, long unsigned int> func(const std::vector<int>&, int)’:
test.cpp:12:62: error: no matching function for call to ‘make_pair<std::size_t, std::size_t>(std::size_t&, std::size_t&)’
           return std::make_pair<std::size_t, std::size_t>(i,j);
                                                              ^
In file included from /usr/include/c++/7/utility:70:0,
                 from test.cpp:1:
/usr/include/c++/7/bits/stl_pair.h:524:5: note: candidate: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
     make_pair(_T1&& __x, _T2&& __y)
     ^~~~~~~~~
/usr/include/c++/7/bits/stl_pair.h:524:5: note:   template argument deduction/substitution failed:
test.cpp:12:62: note:   cannot convert ‘i’ (type ‘std::size_t {aka long unsigned int}’) to type ‘long unsigned int&&’
           return std::make_pair<std::size_t, std::size_t>(i,j);
                                                          ^

既然我们已经明确提到了模板化pair中的类型以及ij的数据类型,为什么还要尝试用unsigned long int替换?

【问题讨论】:

  • std::make_pair&lt;std::size_t, std::size_t&gt; 表示make_pair(size_t&amp;&amp;, size_t&amp;&amp;) 你想如何将左值(如ij)绑定到右值引用?
  • return std::make_pair&lt;std::size_t, std::size_t&gt;(i,j);更改为return {i, j};

标签: c++ templates std-pair forwarding-reference


【解决方案1】:

当你将模板参数指定为std::size_t 时,std::make_pair 的函数参数类型变为std::size_t&amp;&amp;,即右值引用; ij 是左值,不能绑定到右值引用。

只要让std::make_pairstd::make_pair(i,j)那样做模板参数推导(模板参数是std::size_t&amp;,函数参数是std::size_t&amp;)就可以了。 std::make_pair 接受forwarding references,它应该接受左值和右值(对于std::make_pair(0,0),模板参数是std::size_t,函数参数是std::size_t&amp;&amp;)。

【讨论】:

  • 我想了解更多相关信息。 cppreference 没有解释清楚。
  • @InQusitive 更多关于forwarding reference.
猜你喜欢
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 2010-10-12
  • 2013-08-18
  • 2011-01-01
相关资源
最近更新 更多