I didn't understand the passage highlighted below obtained from this article by Thomas Becker:
Given these rules, we can now use rvalue references to solve the perfect forwarding problem as set forth in the previous section. Here's what the solution looks like:template<typename T, typename Arg> shared_ptr<T> factory(Arg&& arg) { return shared_ptr<T>(new T(std::forward<Arg>(arg))); }wherestd::forward
is defined as follows:template<class S>S&& forward(typename remove_reference<S>::type& a) noexcept { return static_cast<S&&>(a); }(Don't pay attention to thenoexcept
keyword for now. It lets the compiler know, for certain optimization purposes, that this function will never throw an exception. We'll come back to it inSection 9.) To see how the code above achieves perfect forwarding, we will discuss separately what happens when our factory function gets called on lvalues and rvalues. LetA
andX
be types. Suppose first thatfactory<A>
is called on an lvalue of typeX
:X x; factory<A>(x);Then, by the special template deduction rule stated above,factory
's template argumentArg
resolves toX&
. Therefore, the compiler will create the following instantiations offactory
andstd::forward
:shared_ptr<A> factory(X& && arg) { return shared_ptr<A>(new A(std::forward<X&>(arg))); } X& && forward(remove_reference<X&>::type& a) noexcept { return static_cast<X& &&>(a); }After evaluating theremove_reference
and applying the reference collapsing rules, this becomes:shared_ptr<A> factory(X& arg) { return shared_ptr<A>(new A(std::forward<X&>(arg))); }
This is the part I didn't follow, probably because I couldn't understand this expression above:
remove_reference<X&>::type& aX& std::forward(X& a)
{return static_cast<X&>(a); }