Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference_wrapper: make_pair VS Class Template Argument Deduction (CTAD)

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?

like image 729
Jonas Avatar asked Nov 26 '18 14:11

Jonas


1 Answers

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.

like image 110
YSC Avatar answered Sep 17 '22 12:09

YSC