0

Why does this code compiles?

#include <utility>

using namespace std;

int main()
{
    int i = 1, j = 2;
    auto p = make_pair(i, j);
    (void) p;
}

And this does not?

#include <utility>

using namespace std;

int main()
{
    int i = 1, j = 2;
    auto p = make_pair<int,int>(i, j);
    (void) p;
}

The only difference is that I explicitly added the template parameters to make_pair. Why does this break the program? GCC gives the following errors:

main.cpp:
 In function 'int main()':
main.cpp:8:37: error: no matching function for call to 'make_pair<int, int>(int&, int&)'
     auto p = make_pair<int,int>(i, j);
                                     ^
In file included from /usr/local/include/c++/7.2.0/utility:70:0,
                 from main.cpp:1:
/usr/local/include/c++/7.2.0/bits/stl_pair.h:519: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/local/include/c++/7.2.0/bits/stl_pair.h:519:5: note:   template argument deduction/substitution failed:
main.cpp:8:37: note:   cannot convert 'i' (type 'int') to type 'int&&'
     auto p = make_pair<int,int>(i, j);
                                     ^

See for example http://coliru.stacked-crooked.com/view?id=15dfe1319882e904.

I know that one may use pair instead of make_pair, so the question is not on how to fix the program; what I am really curious about is why specifying the template parameters of make_pair turns a compiling program in a wrong one.

Giovanni Mascellani
  • 1,218
  • 2
  • 11
  • 26

0 Answers0