【问题标题】:Why is template parameter a reference in this case?为什么在这种情况下模板参数是参考?
【发布时间】:2020-11-29 03:08:27
【问题描述】:

在玩 std::forward 时发现了一个奇怪的行为。这是一个小例子:

#include <type_traits>
#include <iostream>

template <typename A>
void func(A&&)
{
    std::cout
        << std::is_pointer<A>::value
        << std::is_lvalue_reference<A>::value
        << std::is_rvalue_reference<A>::value
        << std::endl;
    using B = typename std::remove_reference<A>::type;
    std::cout
        << std::is_pointer<B>::value
        << std::is_lvalue_reference<B>::value
        << std::is_rvalue_reference<B>::value
        << std::endl;
}

int main()
{
    int* p = nullptr;
    func(p);
}

它打印010100,这意味着A是一个引用而不是一个指针,而std::remove_reference&lt;A&gt;是一个预期的指针。

但是为什么会这样呢?我认为A 是一个指针,A&amp;&amp; 是函数体内的一个引用。另外,如果是这种情况,A&amp;A&amp;&amp; 是什么类型?

【问题讨论】:

    标签: c++ templates template-specialization forwarding-reference


    【解决方案1】:

    这就是forwarding reference 的工作原理;当被传递一个左值时,模板参数A 将被推导出为一个左值引用。对于这种情况,它是int*&amp;,即对指针的左值引用。 (引用折叠后,函数参数的类型也将是int*&amp;。)

    当被传递一个右值时,A 将被推断为非引用类型。例如,如果你传递一个类型为int* 的右值,A 将被推导出为int*。 (那么函数参数的类型就是int*&amp;&amp;。)

    【讨论】:

    • 这是一段我什至不知道的语法。使用template &lt;typename A&gt; func (A&amp;&amp; a1, A&amp; a2, A a3); 之类的函数变得更加清晰,您似乎永远无法调用它
    猜你喜欢
    • 2018-09-08
    • 2017-05-20
    • 2012-09-15
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2021-11-16
    • 2017-07-15
    • 1970-01-01
    相关资源
    最近更新 更多