c++make_pair找不到匹配的函数

c++ make_pair no matching function found

本文关键字:函数 找不到 pair c++make      更新时间:2023-10-16

我有以下代码

        #include <utility>
        using namespace std;
        int a = ...//gets calculated somehow
        int b = ...//same here 
        char container[a][b];
        ...
        std::pair<int, char**> p = make_pair(1, container);

最后一行给我

main.cpp:10:58: error: no matching function for call to 'make_pair(int, char [a][b])'
         std::pair<int, char**> p = make_pair(1, container);
                                                          ^
main.cpp:10:58: note: candidate is:
In file included from /usr/local/include/c++/4.9.2/utility:70:0,
                 from main.cpp:1:
/usr/local/include/c++/4.9.2/bits/stl_pair.h:276:5: note: 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/local/include/c++/4.9.2/bits/stl_pair.h:276:5: note:   template argument deduction/substitution failed:
main.cpp:10:58: note:   variable-sized array type 'char (&)[a][b]' is not a valid template argument
         std::pair<int, char**> p = make_pair(1, container);
                                                          ^
main.cpp:10:32: warning: unused variable 'p' [-Wunused-variable]
         std::pair<int, char**> p = make_pair(1, container);

您的问题有两个方面。首先,静态分配数组的维度必须是编译时常数。可变长度数组(VLA)是非标准的,但某些编译器支持它作为扩展。不过,为了保持程序的标准一致性和可移植性,我会远离这些。

使ab成为const就足够了:

int const a = 5;
int const b = 10;
char container[a][b];

接下来,p的类型与从make_pair(1, container)返回的类型不匹配。在内部,make_pair"衰减"推导出的参数类型(在这种情况下应用数组到指针的转换)。第二个参数container的衰减类型并没有变成char**,而是变成了char (*)[3]——指向第一个元素的指针,而第一个元素本身就是一个数组。

因此,将该行更改为该行应该有效:

std::pair<int, char (*)[3]> p = std::make_pair(1, container);

您可能还想使用auto,这样类型推导就可以减轻混淆:

auto p = std::make_pair(1, container);

并考虑使用std::vector<std::string>而不是C样式的数组。