为什么 make_pair 和类模板参数推导 (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 照原样使用类型。
关于c++ - reference_wrapper : make_pair VS Class Template Argument Deduction (CTAD),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53483124/