C 转发参考和R值参考



我知道转发引用是"对CV UNQUALIFIED模板参数的RVALUE参考",例如

template <class T> void foo(T&& );

这意味着上述函数可以同时使用L值和R值参考。

有我不明白的东西,例如

template <class T>
class A
{
    template <class U>
    void foo(T&& t, U&& u)
    {
        T t2( std::forward(t) ); // or should it be std::move(t)? is T&& forwarding or r-value reference
        U u2( std::forward(u) ); // or should it be std::move(u)? I believe U&& is forwarding reference
    }
};

在上述代码中,既是T&amp; amp;和u&amp;&amp;转发参考?

我编写了一些代码进行测试(VS2015编译器):

class A
{
public:
    A(){};
    A(const A& rhs)
    {
        std::cout << "calling 'const A&' l-value" << std::endl;
    }
    A(A&& rhs)
    {
        std::cout << "calling ' A&&' r-value" << std::endl;
    }
};
template <class T>
class Test
{
public:
    void test1(T&& t)
    {
        T t2(std::forward<T>(t));
    }
    template <typename X>
    void test2(X&& x)
    {
        T t2( std::forward<T>( x ) );
    }
};
void main()
{
    A a;
    Test<A> test;
    test.test1(A());
    test.test1(std::move(a));
    //test.test1(a); // this doesn't compile. error: cannot convert argument 1 from 'A' to 'A &&', You cannot bind an lvalue to an rvalue reference
    test.test2<A>(A());
    test.test2<A>( std::move( a ) );
    //test.test2<A>( a ); // this doesn't compile. error: cannot convert argument 1 from 'A' to 'A &&', You cannot bind an lvalue to an rvalue reference
}

我期待该test.test1(a);test.test2(a)应同时编译,如果它们是转发参考文献,但都不应编译。

有人可以向我解释一下吗?谢谢!

编辑 - - - - - - - 多谢你们 - - - - - -理查德和艺术品是正确的。

这是一个很好的问题,几乎是所有人。

template <class T>
class A
{
    template <class U>
    void foo(T&& t, U&& u);
};

在此示例中,T未推导(您将模板启用时明确定义它)。

U是因为它从参数u推导的。

因此,在几乎所有情况下都将是:

std::move(t);
std::forward<U>(u);

既是T&amp; amp;和u&amp;&amp;转发参考?

no,只有U&&是A 转发参考,因为U是推导的唯一模板参数。实例化A时,T已被"选择"。

除了理查德(Richard)和Artemy指出的内容外,当您指定test.test2<A>( a )时,X类型X已被明确定义为A。

将其更改为test.test2( a )时,应推导X类型并应编译。

最新更新