Quantcast
Channel: Visual C forum
Viewing all articles
Browse latest Browse all 15302

Need some help understanding this

$
0
0

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)));
} 
where std::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 the noexcept 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. Let A and X be types. Suppose first that factory<A> is called on an lvalue of type X:
X x;
factory<A>(x);
Then, by the special template deduction rule stated above, factory's template argument Argresolves to X&. Therefore, the compiler will create the following instantiations of factory 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 the remove_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); }



Viewing all articles
Browse latest Browse all 15302

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>