reference_wrapper: make_pair VS Class Template Argument Deduction (CTAD)

490 views Asked by At

Why does make_pair and Class Template Argument Deduction (CTAD) not agree on which type to generate?

#include <iostream>
#include <functional>
#include <utility>
#include <typeinfo>

int main() {
    int myInt = 5;
    std::reference_wrapper<int> myIntRef = myInt;
    auto myPair = std::make_pair(myInt, myIntRef);
    std::pair My2ndPair(myInt, myIntRef);
    std::cout << typeid(myPair).name() << '\n';
    std::cout << typeid(My2ndPair).name() << '\n';
}

Output:

St4pairIiRiE                       // std::pair<int, int&>
St4pairIiSt17reference_wrapperIiEE // std::pair<int, std::reference_wrapper<int> >

Update:

Why do the deduction guides for std::pair not include a guide for std::reference_wrapper like make_pair has an overload?

2

There are 2 answers

2
YSC On BEST ANSWER

Becase make_pair is smart:

std::reference_wrapper<int> myIntRef = myInt;
auto myPair = std::make_pair(myInt, myIntRef);

This calls the overload unwrapping the std::reference_wrapper<int>:

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

On the other hand, the the implicitly-generated deduction guides for std::pair take the types as-is.

0
Jarod42 On

There is special rule for std::make_pair

The deduced types V1 and V2 are std::decay<T1>::type and std::decay<T2>::type (the usual type transformations applied to arguments of functions passed by value) unless application of std::decay results in std::reference_wrapper<X> for some type X, in which case the deduced type is X&.