我知道转发引用是“对 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&&
and 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)
and test.test2<A>(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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)