【问题标题】:reference_wrapper: make_pair VS Class Template Argument Deduction (CTAD)reference_wrapper:make_pair VS 类模板参数推导(CTAD)
【发布时间】:2018-11-26 14:20:47
【问题描述】:

为什么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 有过载?

【问题讨论】:

    标签: c++ templates c++17 template-argument-deduction


    【解决方案1】:

    因为make_pair聪明的

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

    这调用了overload unwrapping the std::reference_wrapper&lt;int&gt;

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

    另一方面,implicitly-generateddeduction guides for std::pair 采用原样的类型。

    【讨论】:

    【解决方案2】:

    std::make_pair有特殊规则

    推导出的类型 V1 和 V2 是 std::decay&lt;T1&gt;::typestd::decay&lt;T2&gt;::type(通常类型转换应用于按值传递的函数的参数)除非应用 std::decay 导致 std::reference_wrapper&lt;X&gt; 用于某些类型 @987654326 @,此时推导的类型为X&amp;

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多