0

I knew there were probably already some similar questions on StackOverflow, but I didn't actually find anything that fully answered my doubts, so I asked my own question.

There are two different overloads of std::forward:

template< class T >
T&& forward( typename std::remove_reference<T>::type& t );

template< class T >
T&& forward( typename std::remove_reference<T>::type&& t );

What is the difference with one universal reference template function using static_cast? Like:

template<class T>
T&& myForward(T &&t) {
    return static_cast<T&&>(t);
}

When I pass a rvalue of type A, T with be deduced to A and myForward will return A &&; When a lvalue is passed, T with be deduced to A &, and it will return A &. So what is the difference?

I understand the notion that the second overload can prohibit forwarding a rvalue to a lvalue, but why myForward cannot?

Junhui Zhu
  • 93
  • 5
  • 1
    The second overload prevents/prohibits passing rvalues as lvalues. [cppreference](https://en.cppreference.com/w/cpp/utility/forward) – Adrian Mole Sep 06 '22 at 15:46
  • It's strange that I could google the dupe for a second, but you could not, and spent a minute at least for writing the question. – 273K Sep 06 '22 at 15:47
  • Adrian could you give me a more concrete example of this kind of behavior? – Junhui Zhu Sep 06 '22 at 15:56
  • `myForward` will deduce `T` from the arg, like `myForward(int())`, that is not desired, because all params of a caller are lvalues. – 273K Sep 06 '22 at 16:02
  • You mean because we also want to pass lvalue as rvalue, so `myForward` is not enough? – Junhui Zhu Sep 06 '22 at 16:06
  • Sorry I did not get you, I thought `static_cast` will convert lvalue arguments to rvalues. – Junhui Zhu Sep 06 '22 at 16:09
  • I mean `myForward` leads to hard to debug bugs. On of possible bugs is described in the dupe. – 273K Sep 06 '22 at 16:09
  • Thinking about lack of competence of C++ Committee and C++ standard library authors is not productive. The dupe has a reference to the proposal, it very clearly explains the reason for such implementation with a visual table. – 273K Sep 06 '22 at 16:13

0 Answers0