3

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.

Community
  • 1
  • 1
Puppy
  • 144,682
  • 38
  • 256
  • 465

1 Answers1

6

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).

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • You know, I realize that the structure of my question is at fault here, but the answer doesn't actually answer the question, which is why an explicit type argument is required. I've got as far as the existing implementation, but not why that's needed, or rather, I get for why the two-argument version exists, but why no overload for a single argument. – Puppy Jul 09 '11 at 21:02
  • This is a duplicate, I finally found the other question (which you answered) and I'm voting to close – Puppy Jul 09 '11 at 21:14