c++ - std::pair 替换因 std::size_t 失败

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

#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 中的类型以及 i 的数据类型时,为什么它尝试用 unsigned long int 替换和j

最佳答案

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

只需让 std::make_pair 进行模板参数推导,如 std::make_pair(i,j) (模板参数为 std::size_t&,函数参数是 std::size_t&) 就可以了。 std::make_pair 需要 forwarding references ,它应该接受左值和右值(对于 std::make_pair(0,0),模板参数是 std::size_t,函数参数是 std::size_t&&)。

关于c++ - std::pair 替换因 std::size_t 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68235631/

相关文章:

c++ - 未定义的行为和顺序点

c++ - 具有模板化构造函数以及复制和移动构造函数的类

c++ - 如何获取元组的一部分?

c++ - 将对值分配给映射键时出错

C++ 对和指针

C++ 文件处理 - 输出与输入不匹配

c++ - 字符数组和指针的基本混淆

c++ - 为什么 .join 仍然是必要的,当所有其他线程都在主线程之前完成时?

c++ - 类型定义类

C++对删除错误