【发布时间】:2018-02-10 06:42:42
【问题描述】:
我了解转发引用是“对 cv 不合格模板参数的右值引用”,例如在
template <class T> void foo(T&& );
这意味着上面的函数可以同时接受左值和右值引用。
有些东西我不明白,例如
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编译器):
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) 如果它们正在转发引用,它们都应该编译,但两者都没有。
有人可以向我解释一下吗?谢谢!
编辑 - - - - - - - 多谢你们 - - - - - - Richard 和 Artemy 是正确的。
【问题讨论】:
-
无关,我不知道在这个时代,VS2015 工具链接受
void main()是可悲还是超现实。真的吗? -
在你最后一个关闭的情况下 U 没有被推导出 - 所以你的情况不会编译。为了使其可演绎,将其称为 test.test2(a);并在测试 2 中将 forward
更改为 forward
标签: c++ rvalue-reference forwarding-reference