reference_wrapper: make_pair VS Class 模板参数推导 (CTAD)

reference_wrapper: make_pair VS Class Template Argument Deduction (CTAD)

为什么 make_pair 和 Class 模板参数推导 (CTAD) 不同意生成哪种类型?

#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';
}

输出:

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

更新:

为什么 std::pair 的推导指南不包含 std::reference_wrapper 的指南,例如 make_pair 有超载?

因为 make_pair 聪明:

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

这调用了 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);

另一方面,implicitly-generated deduction guides for std::pair 照原样使用类型。

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&.