开发者

The structure of std::forward [duplicate]

This question already has an answer her开发者_如何学运维e: Closed 11 years ago.

Possible Duplicate:

Why use identity in forward definition for C++0x rvalue reference?

I'm really curious- why does std::forward require an explicit template parameter? Couldn't it be simply

template<typename T> T forward(T&& ref) {
    return ref;
}

I'd really like all the relevant detail, not simplifications, if possible.


Your implementation makes it impossible to forward an lvalue as an rvalue. With an lvalue A, T deduces as A&, and thus A& is your return type (an lvalue).

See N2951 for a list of use cases forward is meant to be applicable to.

The need to forward an lvalue as an rvalue comes about in the perfect forwarding use case:

template <class T>
void bar(T&& t);

template <class T>
void foo(T&& t)
{
    bar(std::forward<T>(t));
}

Inside foo t is always an lvalue. Consider the case foo(A()). T deduces as A, and you want to forward t as an rvalue A, even though t is an lvalue.

forward<A>(t);

casts the lvalue t to A&& (an rvalue).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜