C ++转发参考和R值参考 [英] C++ forwarding reference and r-value reference
问题描述
我知道转发引用是对cv不合格模板参数的右值引用",例如
I understand that a forwarding reference is "an rvalue reference to a cv-unqualified template parameter", such as in
template <class T> void foo(T&& );
这意味着上面的函数可以同时使用l值和r值引用.
which means the above function can take both l-value and r-value reference.
有些事情我不理解,例如
There's something I don't understand, e.g.
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&&和U&&转发参考?
我写了一些代码进行测试(VS2015编译器):
I wrote some code to test (VS2015 compiler):
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)正在转发引用,则两者都应编译,但两者都不应该.
I was expecting that test.test1(a); and test.test2(a) should both compile if they are forwarding references, but neither does.
有人可以向我解释吗?谢谢!
Could someone explain this to me? Thanks!
修改- - - - - - - 谢谢你们 - - - - - -理查德(Richard)和阿尔蒂(Artemy)是正确的.
Edit --------------thanks, guys----------- Richard and Artemy are correct.
推荐答案
这是一个很好的问题,一开始几乎困扰所有人.
It's a great question which foxes almost everyone in the beginning.
template <class T>
class A
{
template <class U>
void foo(T&& t, U&& u);
};
在此示例中,未推导 T
(您在实例化模板时明确定义了它).
In this example, T
is not deduced (you explicitly define it when you instanciate the template).
U
是因为它是从参数 u
推导出来的.
U
is deduced because it's deduced from the argument u
.
因此,几乎在所有情况下都是:
Therefore, in almost all cases it would be:
std::move(t);
std::forward<U>(u);
这篇关于C ++转发参考和R值参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!