<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>forward</title>

	<style>
	p {text-align:justify}
	li {text-align:justify}
	blockquote.note
	{
		background-color:#E0E0E0;
		padding-left: 15px;
		padding-right: 15px;
		padding-top: 1px;
		padding-bottom: 1px;
	}
	ins {color:#00A000}
	del {color:#A00000}
	</style>
</head>
<body>

<address align=right>
Document number: N2951=09-0141<br/>
<br/>
<a href="mailto:howard.hinnant@gmail.com">Howard E. Hinnant</a><br/>
2009-09-27
</address>
<hr/>
<h1 align=center><tt>forward</tt></h1>

<h2>Introduction</h2>

<p>
There is a fundamental disagreement in the design philosophy over <tt>std::forward</tt>.
One camp believes that <tt>forward</tt> should only be used in a very specific
pattern, namely:
</p>

<blockquote><pre>
template &lt;class T&gt;
void f(T&amp;&amp; x)
{
    <font color="#C80000">// x is an lvalue here.  If the actual argument to f was an</font>
    <font color="#C80000">// rvalue, pass static_cast&lt;T&amp;&amp;&gt;(x) to g; otherwise, pass x.</font>
    g( forward&lt;T&gt;(x) );
}
</pre></blockquote>

<p>
and all other uses by our customers should be forbidden.
</p>

<p>
The fundamental disagreement is that I do not believe it is possible, or even a
good idea, to try to define the semantics of a function by attempting to limit
its use to a very specific coding pattern.  Instead a function's design should
be based on its inputs, outputs and side effects.  With this particular function
there should be no side effects, so we only need to decide what inputs are appropriate
and what the corresponding output should be.
</p>
<p>
We, as a committee, are not 
sufficiently prescient to foresee all of the ingeniously clever applications
any tool might be used for.
</p>

<p>
Where would C++ be today if its design had followed a philosophy that there was
only one right way to code, and all other styles should be shunned, and outright
prevented where possible?  I believe this would be a very different (and inferior)
language today had the committee had such a mindset in the 1990's.
</p>

<p>
Use cases backed up by testing of those use cases should drive a function's interface
design.  Which use cases provide beneficial behavior?  Which are likely to lead
to accidental run time errors?  Which use cases provide both benefit and risk,
and does the benefit outweigh the risk?
</p>

<p>
This paper reviews six proposed implementations of <tt>std::forward</tt>
(from both sides of the disagreement) and
tests each of them against six use cases.  Some of those use cases will lead
to dangling references (which is bad).  And some of the use cases will offer truly
useful and safe functionality.  This paper will favor those implementations
of <tt>std::forward</tt> which allow the client maximum utility while giving
compile time diagnostics which prevent the use cases which would otherwise lead
to run time errors.
</p>

<p>
The conclusions of this paper are previewed here for those who prefer to
just "get to the point".  The use cases are labeled A - F, and the
implementations 0 - 5.  Case 0 is equivalent to just using
<tt>static_cast&lt;T&amp;&amp;&gt;</tt> (which has been suggested). 
Only implementation 5 of <tt>std::forward</tt> passes all use cases
without error, and is strongly recommended by this paper:
</p>

<blockquote>
<table border="1">
<caption>
<tt>forward</tt> implementation results for each use case
</caption>

<tr>
<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>score</th>
</tr>

<tr>
<th>0</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td align="right">67%</td>
</tr>

<tr>
<th>1</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td align="right">50%</td>
</tr>

<tr>
<th>2</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td align="right">50%</td>
</tr>

<tr>
<th>3</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td align="right">83%</td>
</tr>

<tr>
<th>4</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td align="right">83%</td>
</tr>

<tr>
<th>5</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td align="right">100%</td>
</tr>
</table>

<blockquote>
<dl>
<dt><font color="#C80000">cfail</font></dt>
    <dd>A compile time failure.</dd>
<dt><font color="#C80000">rfail</font></dt>
    <dd>A run time failure.</dd>
</dl>
</blockquote>
</blockquote>

<h2>Terminology</h2>

<p>
<tt>std::forward&lt;T&gt;(t)</tt> is, at the end of the day, a
<tt>static_cast&lt;T&amp;&amp;&gt;(t)</tt>.  Nothing more, and possibly
less.  And the question really is:  How much less should it be?
</p>

<p>
To describe the domain and range of this function, this paper will use terms such
as:
</p>

<blockquote>
forward an lvalue <tt>t</tt> as an rvalue <tt>T</tt>
</blockquote>

<p>
In code, this means:
</p>

<blockquote><pre>
static_cast&lt;T&amp;&amp;&gt;(t);
</pre></blockquote>

<p>
where <tt>t</tt> is known to be an lvalue expression, and <tt>T</tt> is known to
be an object or function type (not a reference type).  In general, the type of
<tt>t</tt> need not be the same as the type of <tt>T</tt>.  This paper will explore
that aspect with use cases as well.
</p>

<p>
Forwarding an lvalue <tt>t</tt> as an lvalue <tt>T</tt> is quite similar:
</p>

<blockquote><pre>
static_cast&lt;T&amp;&gt;(t);
</pre></blockquote>

<p>
<tt>t</tt> might also represent an rvalue expression, in which case we then speak
of forwarding an rvalue <tt>t</tt> as an lvalue or rvalue <tt>T</tt> (again using
the same <tt>static_cast</tt> expressions).
</p>

<p>
There is nothing in this paper that is any deeper than these <tt>static_cast</tt>
expressions.
</p>

<h2><tt>forward</tt> Implementations</h2>

<p>
There are six <tt>forward</tt> implementations explored in this paper and they
will be labeled 0 thru 5.  I've chosen 0 to be an implementation which most closely
mimics the behavior of <tt>forward</tt> we voted into the WP in April 2007 in Oxford.
All implementations presented herein reflect the language rules in effect since
after the July 2009 Frankfurt meeting (no concepts, lvalues can not implicitly
bind to an rvalue reference).
</p>

<ol start="0">
<li>
<p>
A base case reformulated without <tt>identity</tt>, and reflecting the design of
<tt>forward</tt> up until
the language change prohibiting lvalues from implicitly binding to rvalue references (but
reformulated to work with that language change).
Note that this choice is also equivalent to the suggestion "just use <tt>static_cast&lt;T&amp;&amp;&gt;</tt>."
</p>

<blockquote><pre>
template &lt;class T, class U&gt;
inline
T&amp;&amp;
forward(U&amp;&amp; u)
{
    return static_cast&lt;T&amp;&amp;&gt;(u);
}
</pre></blockquote>
</li>

<li>
<p>
Suggestion 1 given by David Abrahams in the 2009-08-02 comment of
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1054">LWG 1054</a>
with the following rationale:
</p>

<blockquote>
Use a simple definition of forward that accomplishes its original
purpose without complications to accomodate other uses.
</blockquote>

<blockquote><pre>
template &lt;class T, class U&gt;
T&amp;&amp; forward(U&amp; u)
{
    return static_cast&lt;T&amp;&amp;&gt;(u);
}
</pre></blockquote>

</li>

<li>
<p>
Suggestion 2 given by David Abrahams in the 2009-08-02 comment of
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1054">LWG 1054</a>
with the following rationale:
</p>

<blockquote>
Use a definition of forward that protects the user from as many
potential mistakes as possible, by actively preventing all other uses.
</blockquote>

<blockquote><pre>
template &lt;class T, class U&gt;
boost::enable_if_c&lt;
    is_lvalue_reference&lt;U&gt;::value
    &amp;&amp; !is_rvalue_reference&lt;T&gt;::value
    &amp;&amp; is_same&lt;T&amp;,U&amp;&gt;::value
    , T&amp;&amp;&gt;::type forward(U&amp;&amp; a)
{
    return static_cast&lt;T&amp;&amp;&gt;(a);
}
</pre></blockquote>

</li>

<li>
<p>
An implementation that allows forwarding an rvalue as an rvalue, but not an rvalue
as an lvalue, and places no
restriction on type conversions.
</p>

<blockquote><pre>
template &lt;class T, class U,
    class = typename enable_if&lt;
         is_lvalue_reference&lt;T&gt;::value ?
             is_lvalue_reference&lt;U&gt;::value :
             true
    &gt;::type&gt;
inline
T&amp;&amp;
forward(U&amp;&amp; u)
{
    return static_cast&lt;T&amp;&amp;&gt;(u);
}
</pre></blockquote>

<p>
Note:  This constraint is equivalent to that shown in my 2009-08-02 comment of
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1054">LWG 1054</a>.
This is just another way to write it.
</p>

</li>

<li>
<p>
Similar to #3 but with additional constraints preventing base type conversions
(like #2), but it doesn't prevent adding cv-qualifiers (unlike #2).  This is
also what I say is my preferred solution in the 2009-08-02 comment of
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#1054">LWG 1054</a>.
However after Jason expressed some concerns and I investigated/tested the use
cases Jason described, I have become convinced the next design is better.
</p>

<blockquote><pre>
template &lt;class T&gt;
struct __base_type
{
    typedef typename remove_cv&lt;typename remove_reference&lt;T&gt;::type&gt;::type type;
};

template &lt;class T, class U,
    class = typename enable_if&lt;
         (is_lvalue_reference&lt;T&gt;::value ?
             is_lvalue_reference&lt;U&gt;::value :
             true) &amp;&amp;
         is_same&lt;typename __base_type&lt;T&gt;::type,
                 typename __base_type&lt;U&gt;::type&gt;::value
    &gt;::type&gt;
inline
T&amp;&amp;
forward(U&amp;&amp; u)
{
    return static_cast&lt;T&amp;&amp;&gt;(u);
}
</pre></blockquote>

</li>

<li>
<p>
Similar to #4 but not as restrictive.  It allows any conversion in which a
temporary is not created as a result of the conversion.  This includes a derived
to base conversion (credit Jason Merrill for the problem identification).
</p>

<blockquote><pre>
template &lt;class T, class U,
    class = typename enable_if&lt;
         (is_lvalue_reference&lt;T&gt;::value ?
             is_lvalue_reference&lt;U&gt;::value :
             true) &amp;&amp;
         is_convertible&lt;typename remove_reference&lt;U&gt;::type*,
                        typename remove_reference&lt;T&gt;::type*&gt;::value
    &gt;::type&gt;
inline
T&amp;&amp;
forward(U&amp;&amp; u)
{
    return static_cast&lt;T&amp;&amp;&gt;(u);
}
</pre></blockquote>

</li>

</ol>

<p>
<b>Emphasis:</b>  Every implementation simply does a
<tt>static_cast&lt;T&amp;&amp;&gt;(u)</tt>.  The only question is what are the
constraints on <tt>T</tt> and <tt>U</tt> when calling <tt>forward</tt>.
</p>

<h2>Use Cases</h2>

<p>
Six use cases will be presented:
</p>

<ol type="A">
<li>
<b>Should forward an lvalue as an lvalue.</b>  All implementations pass this test.  But this
is not the classic perfect forwarding pattern.  The purpose of this test is to
show that implementation 2 fails in its stated goal of preventing all use cases
except perfect forwarding.
</li>

<li>
<b>Should forward an rvalue as an rvalue.</b>  Like use case A, this is an identity
transformation and this presents a motivating example where the identity transformation is
needed.
</li>

<li>
<b>Should <em>not</em> forward an rvalue as an lvalue.</b>  This use case demonstrates
a dangerous situation of accidentally creating a dangling reference.
</li>

<li>
<b>Should forward less cv-qualified expressions to more cv-qualified expressions.</b>
A motivating use case involving the addition of <tt>const</tt> during the <tt>forward</tt>.
</li>

<li>
<b>Should forward expressions of derived type to an accessible, unambiguous base type.</b>
A motivating use case involving forwarding a derived type to a base type.
</li>

<li>
<b>Should <em>not</em> forward arbitrary type conversions.</b>  This use case demonstrates
how arbitrary conversions within a <tt>forward</tt> lead to dangling reference run time errors.
</li>

</ol>

<p>
Each use case was chosen to help direct a specific design decision with regards to
<tt>std::forward</tt>.  Thus the design is driven by both engineering judgement <em>and</em>
empirical evidence and testing.
These use cases also represent reasonable code our customers may write using
<tt>std::forward</tt>.  All of the use cases are quite similar to each other in
the hopes of easing the presentation.
</p>

<h3>A. Should forward an lvalue as an lvalue</h3>

<p>
All of the use cases center around a container <tt>C&lt;T&gt;</tt> which is
somewhat like <tt>std::pair</tt> and <tt>std::tuple</tt> in that the
container can contain either object types <tt>T</tt> (such as <tt>int</tt>) or
reference types <tt>T</tt> (such as <tt>const int&amp;</tt>).
</p>

<p>
The container has a converting constructor that takes an rvalue container of
some other type <tt>U</tt>, and extracts the <tt>T</tt> from the <tt>U</tt>
via a member getter (named <tt>get()</tt>).  Because the container <tt>U</tt>
is known to be an rvalue, it is recast to an rvalue (using <tt>std::move()</tt>)
prior to calling the member <tt>get()</tt> in the hopes of choosing the right
overload as this container may make use of <i>rvalue-this</i> qualifiers.
<tt>forward</tt> is used instead of <tt>move</tt> in this constructor so as to
correctly handle the case when <tt>T</tt> is an lvalue reference type.
</p>

<blockquote><pre>
#include &lt;iostream&gt;
#include &lt;list&gt;

template &lt;class T&gt;
struct C
{
    T t_;

    template &lt;class U,
              class = typename std::enable_if
                    &lt;
                        !std::is_lvalue_reference&lt;U&gt;::value
                    &gt;::type&gt;
        C(U&amp;&amp; u) : t_(<b>std::forward&lt;T&gt;</b>(std::move(u).get())) {}
};

class A
{
    int data_;
public:
    explicit A(int data = 1)
        : data_(data) {}
    ~A() {data_ = -1;}

    void test() const
    {
        if (data_ &lt; 0)
            std::cout &lt;&lt; "A is destructed\n";
        else
            std::cout &lt;&lt; "A = " &lt;&lt; data_ &lt;&lt; '\n';
    }
};

class Awrap
{
    const A&amp; a_;
public:
    explicit Awrap(const A&amp; a) : a_(a) {}
    <b>const A&amp;</b> get() const {return a_;}
};

template &lt;class C&gt;
void test(C c)
{
    c.t_.test();
}

int main()
{
    std::list&lt;C&lt;<b>const A&amp;</b>&gt; &gt; list;
    A a(3);
    C&lt;<b>const A&amp;</b>&gt; c((Awrap(a)));
    list.push_back(c);
    test(c);
    test(list.front());
}
</pre></blockquote>

<p>
In this use case the value type of <tt>C</tt> is <tt>const A&amp;</tt>.  The
secondary container is named <tt>Awrap</tt> and is reminiscent of <tt>std::ref</tt>
(<tt>Awrap</tt> is not absurd or exceedingly rare code).  It stores a <tt>const A&amp;</tt>
and its getter returns a <tt>const A&amp;</tt>.  The <tt>forward</tt> function
in <tt>C's</tt> constructor forwards a <tt>const A&amp;</tt> as a <tt>const A&amp;</tt>.
</p>

<p>
All 6 implementations compile and output:
</p>

<blockquote><pre>
A = 3
A = 3
</pre></blockquote>

<p>
which is the expected, safe and useful answer for this use case.  However this
is not the prototypical "perfect forwarding" example shown at the beginning of
this paper.  The fact that implementation 2 allows this use case
is contrary to the rationale given for that implementation.
</p>

<h3>B. Should forward an rvalue as an rvalue</h3>

<p>
This use case is nearly identical to use case A.  Instead of <tt>C</tt>'s value
type of <tt>const A&amp;</tt>, now it is simply <tt>A</tt>.  And instead of the
secondary container's getter returning <tt>A const&amp;</tt> it just returns
<tt>A</tt>.  The code for the container <tt>C</tt>'s constructor is <em>identical</em>.
This is no accident as the design of the container <tt>C</tt> is intended to
cover <em>both</em> use cases:
</p>

<blockquote><pre>
#include &lt;iostream&gt;
#include &lt;list&gt;

template &lt;class T&gt;
struct C
{
    T t_;

    template &lt;class U,
              class = typename std::enable_if
                    &lt;
                        !std::is_lvalue_reference&lt;U&gt;::value
                    &gt;::type&gt;
        C(U&amp;&amp; u) : t_(std::forward&lt;T&gt;(std::move(u).get())) {}
};

class A
{
    int data_;
public:
    explicit A(int data = 1)
        : data_(data) {}
    ~A() {data_ = -1;}

    void test() const
    {
        if (data_ &lt; 0)
            std::cout &lt;&lt; "A is destructed\n";
        else
            std::cout &lt;&lt; "A = " &lt;&lt; data_ &lt;&lt; '\n';
    }
};

class Awrap
{
    A a_;
public:
    explicit Awrap(const A&amp; a) : a_(a) {}
    <b>A</b> get() const {return a_;}
};

template &lt;class C&gt;
void test(C c)
{
    c.t_.test();
}

int main()
{
    std::list&lt;C&lt;<b>A</b>&gt; &gt; list;
    A a(3);
    C&lt;<b>A</b>&gt; c((Awrap(a)));
    list.push_back(c);
    test(c);
    test(list.front());
}
</pre></blockquote>

<p>
Implementations 0, 3, 4 and 5 compile this use case and output the safe and
expected answer:
</p>

<blockquote><pre>
A = 3
A = 3
</pre></blockquote>

<p>
Implementations 1 and 2 fail to compile the example because <tt>Awrap::get()</tt>
returns an rvalue, and in these implementations one can not forward an rvalue
as an rvalue.  That is:
</p>

<blockquote><pre>
static_cast&lt;A&amp;&amp;&gt;(A());
</pre></blockquote>

<p>
is disallowed.
If it is not ok for <tt>forward</tt> to allow use case B, why is it ok for it to
allow use case A?
</p>

<p>
Indeed, I can see no reason at all that this is not a safe, valid and motivating
use case.
</p>

<h3>C. Should <em>not</em> forward an rvalue as an lvalue</h3>

<p>
To demonstrate this next use case, I start with exactly use case A (the one that
everyone passes) and introduce a programming mistake that could easily happen
by accident:  the removal a single ampersand from the return type of
<tt>Awrap::get()</tt>, accidentally changing the return type from a <tt>const</tt>
lvalue to a <tt>const</tt> rvalue (though I've seen code in the wild which purposefully
returns <tt>const</tt> rvalues).
</p>

<blockquote><pre>
#include &lt;iostream&gt;
#include &lt;list&gt;

template &lt;class T&gt;
struct C
{
    T t_;

    template &lt;class U,
              class = typename std::enable_if
                    &lt;
                        !std::is_lvalue_reference&lt;U&gt;::value
                    &gt;::type&gt;
        C(U&amp;&amp; u) : t_(std::forward&lt;T&gt;(std::move(u).get())) {}
};

class A
{
    int data_;
public:
    explicit A(int data = 1)
        : data_(data) {}
    ~A() {data_ = -1;}

    void test() const
    {
        if (data_ &lt; 0)
            std::cout &lt;&lt; "A is destructed\n";
        else
            std::cout &lt;&lt; "A = " &lt;&lt; data_ &lt;&lt; '\n';
    }
};

class Awrap
{
    const A&amp; a_;
public:
    explicit Awrap(const A&amp; a) : a_(a) {}
    <b>const A<del>&amp;</del></b> get() const {return a_;}
};

template &lt;class C&gt;
void test(C c)
{
    c.t_.test();
}

int main()
{
    std::list&lt;C&lt;<b>const A&amp;</b>&gt; &gt; list;
    A a(3);
    C&lt;<b>const A&amp;</b>&gt; c((Awrap(a)));
    list.push_back(c);
    test(c);
    test(list.front());
}
</pre></blockquote>

<p>
Implementations 0 and 1 compile this code and output:
</p>

<blockquote><pre>
A = 2097536A
A = 10
</pre></blockquote>

<p>
which represent garbage answers (a run time error).  What has happened is that
the lvalue <tt>const A&amp;</tt> in <tt>C</tt> has been bound to an rvalue
which quickly goes out of scope and gets destructed, resulting in a dangling
reference when <tt>C.t_</tt> is later referenced. 
</p>

<p>
Note that implementation 0 purposefully, and wrongly, allows forwarding an rvalue
to an lvalue.  Also note that implementation 1 attempts to prevent forwarding
any rvalues at all, but does indeed forward an rvalue as an lvalue in this use
case.  Implementation 1 fails to prevent what it is trying to prevent.
</p>

<p>
Implementations 2, 3, 4 and 5 all (rightly) fail to compile use case C, and thus
catch this run time error at compile time.
</p>

<p>
So far we have explored two useful identity use cases and one use case which makes a
dangerous change from rvalue to lvalue.  Implementations 1 and 2 failed to compile
one of the useful identity cases, and implementations 0 and 1 gave run time
errors in the dangerous use case.  Only implementations 3, 4 and 5 had good
behavior in these first 3 use cases.
</p>

<p>
The next 3 use cases will concentrate on the impact of changing types during
the forward.
</p>

<h3>D. Should forward less cv-qualified expressions to more cv-qualified expressions</h3>

<p>
This use case explores the impact of <em>adding</em> <i>cv</i>-qualifications
under the <tt>forward</tt>.  Subtracting <i>cv</i>-qualifications is not considered
by any of these implementations as <tt>static_cast</tt> disallows such
transformations (<tt>const_cast</tt> would be needed for that).
</p>

<blockquote><pre>
#include &lt;iostream&gt;
#include &lt;list&gt;

template &lt;class T&gt;
struct C
{
    T t_;

    template &lt;class U,
              class = typename std::enable_if
                    &lt;
                        !std::is_lvalue_reference&lt;U&gt;::value
                    &gt;::type&gt;
        C(U&amp;&amp; u) : t_(std::forward&lt;T&gt;(std::move(u).get())) {}
};

class A
{
    int data_;
public:
    explicit A(int data = 1)
        : data_(data) {}
    ~A() {data_ = -1;}

    void test() const
    {
        if (data_ &lt; 0)
            std::cout &lt;&lt; "A is destructed\n";
        else
            std::cout &lt;&lt; "A = " &lt;&lt; data_ &lt;&lt; '\n';
    }
};

class Awrap
{
    A&amp; a_;
public:
    explicit Awrap(A&amp; a) : a_(a) {}
    <b>const A&amp; get() const {return a_;}
          A&amp; get()       {return a_;}</b>
};

template &lt;class C&gt;
void test(C c)
{
    c.t_.test();
}

int main()
{
    std::list&lt;C&lt;const A&amp;&gt; &gt; list;
    A a(3);
    C&lt;const A&amp;&gt; c((Awrap(a)));
    list.push_back(c);
    test(c);
    test(list.front());
}
</pre></blockquote>

<p>
The only difference between use case A, and use case D, is that in D <tt>Awrap</tt>'s
getters are now overloaded on <tt>const</tt>, much like all of the standard
containers are overloaded on <tt>const</tt> for <tt>front()</tt> and <tt>back()</tt>.
Also <tt>Awrap</tt> is now holding an <tt>A&amp;</tt> instead of a <tt>const A&amp;</tt>.
</p>

<p>
In this use case <tt>forward</tt> is being asked to cast an <tt>A&amp;</tt> to a
<tt>const A&amp;</tt>.  This should be a safe (and often needed) situation.
Please note that for all of these use cases (A, B, C and D), the implementation
of <tt>C&lt;T&gt;</tt> <em>has not changed</em>.  <tt>C&lt;T&gt;</tt> is designed
to handle all of these cases properly.
</p>

<p>
Implementations 0, 1, 3, 4, and 5 compile this code and output:
</p>

<blockquote><pre>
A = 3
A = 3
</pre></blockquote>

<p>
Implementation 2 fails to compile as it constrains the <tt>static_cast</tt> to
not add <tt>const</tt>.  Also note that the supporters of implementation 2 will
argue that <tt>forward</tt> shouldn't be used in this context anyway; just use
<tt>static_cast&lt;T&amp;&amp;&gt;</tt>.  But note that <u>this very advice leads
our customer into an otherwise preventable run time error</u>, as demonstrated by use case C.
</p>

<p>
So far, only implementations 3, 4 and 5 have passed (or correctly refused to compile) all
use cases.  The next two use cases will differentiate these three implementations
from each other.
</p>

<h3>E. Should forward expressions of derived type to an accessible, unambiguous base type</h3>

<p>
In this use case an extra constructor is added to <tt>C&lt;T&gt;</tt>.
The purpose of this constructor is to serve as the move constructor of the container.
Additionally, a new client writes <tt>Derived&lt;T&gt;</tt> which derives from
<tt>C&lt;T&gt;</tt>.  In this use case we explore how to write the move constructor
for <tt>Derived&lt;T&gt;</tt>.
</p>

<blockquote><pre>
#include &lt;utility&gt;

template &lt;class T&gt;
struct C
{
    T t_;

    C() {}

    template &lt;class U,
              class = typename std::enable_if
                    &lt;
                        !std::is_lvalue_reference&lt;U&gt;::value
                    &gt;::type&gt;
        C(U&amp;&amp; u) : t_(std::forward&lt;T&gt;(std::move(u).get())) {}

    C(C&amp;&amp; c) : t_(std::forward&lt;T&gt;(c.t_)) {}
};

template &lt;class T&gt;
struct Derived
    : C&lt;T&gt;
{
    Derived() {}
    Derived(Derived&amp;&amp; d) : C&lt;T&gt;(std::move(d)) {}
};

int main()
{
    Derived&lt;int&gt; d;
    Derived&lt;int&gt; d2(std::move(d));
}
</pre></blockquote>

<p>
The above is our first attempt at the move constructor for <tt>Derived&lt;T&gt;</tt>.
It simply casts <tt>d</tt> to an rvalue using <tt>move</tt> and then passes it to
the base class.  Unfortunately this does not compile:
</p>

<blockquote><pre>
error: 'struct Derived&lt;int&gt;' has no member named 'get'
</pre></blockquote>

<p>
Unfortunately <tt>C&lt;T&gt;</tt>'s generic constructor is being called instead
of the intended move constructor for <tt>C&lt;T&gt;</tt>.  A smart thing to do
would be to further constrain <tt>C&lt;T&gt;</tt>'s generic constructor
to not accept things that aren't a <tt>C</tt> or that don't have <tt>C</tt> as
a base class.  However, let's say that the author of <tt>Derived</tt> does
not have write access to <tt>C</tt>'s source code (a common case in the real world).
</p>

<p>
Now the author of <tt>Derived</tt> must deal with this within his own move
constructor.  There are three possibilities:
</p>

<ol>
<li><blockquote><pre>
Derived(Derived&amp;&amp; d) : C&lt;T&gt;(std::move(static_cast&lt;C&lt;T&gt;&amp;&gt;(d))) {}
</pre></blockquote></li>
<li><blockquote><pre>
Derived(Derived&amp;&amp; d) : C&lt;T&gt;(static_cast&lt;C&lt;T&gt;&amp;&amp;&gt;(d)) {}
</pre></blockquote></li>
<li><blockquote><pre>
Derived(Derived&amp;&amp; d) : C&lt;T&gt;(std::forward&lt;C&lt;T&gt;&gt;(d)) {}
</pre></blockquote></li>
</ol>

<p>
In my opinion, #3 wins hands down in the clarity/readability department.  It
says that you are going to forward the lvalue <tt>d</tt> of type <tt>Derived&lt;T&gt;</tt>
as an rvalue of type <tt>C&lt;T&gt;</tt>.  At the very least, #3 is a very
reasonable choice for our customers to make.
</p>

<p>
Implementations 0, 1, 3 and 5 allow our customer to write his constructor as
shown above using <tt>forward</tt>.  Implementations 2 and 4 disallow it.  I
see no rationale to disallow it.  The resulting code is safe, clear and useful.
</p>

<p>
A subtle but critically important fact to note is that in the expression:
</p>

<blockquote><pre>
static_cast&lt;C&lt;T&gt;&amp;&amp;&gt;(d);
</pre></blockquote>

<p>
which is found inside of the <tt>forward</tt>: no temporary is generated as a
result of the <tt>static_cast</tt>.   This brings us to our last use case
which <em>does</em> generate a temporary during the <tt>static_cast</tt>.
</p>

<h3>F.  Should <em>not</em> forward arbitrary type conversions</h3>

<p>
In this last use case a "converting move constructor" is written for our
container <tt>C&lt;T&gt;</tt>.  This is much like the converting move
constructor you might find in standard classes such as <tt>tuple</tt> and
<tt>unique_ptr</tt>.
</p>

<blockquote><pre>
#include &lt;iostream&gt;
#include &lt;utility&gt;
#include &lt;type_traits&gt;

template &lt;class T&gt;
struct C
{
    T t_;

    C() {}

    explicit C(const T&amp; t) : t_(t) {}

    template &lt;class U,
              class = typename std::enable_if
                    &lt;
                        std::is_convertible&lt;U, T&gt;::value
                    &gt;::type&gt;
        C(C&lt;U&gt;&amp;&amp; c) : t_(std::forward&lt;T&gt;(c.t_)) {}
};

class B;

class A
{
    int data_;

    friend class B;
public:
    explicit A(int data = 1)
        : data_(data) {}
    ~A() {data_ = -1;}

    void test() const
    {
        if (data_ &lt; 0)
            std::cout &lt;&lt; "A is destructed\n";
        else
            std::cout &lt;&lt; "A = " &lt;&lt; data_ &lt;&lt; '\n';
    }
};

class B
{
    int data_;
public:
    explicit B(int data = 1)
        : data_(data) {}
    B(const A&amp; a) : data_(a.data_) {}
    B(A&amp;&amp; a) : data_(a.data_) {a.data_ = 100;}
    ~B() {data_ = -1;}

    void test() const
    {
        if (data_ &lt; 0)
            std::cout &lt;&lt; "B is destructed\n";
        else
            std::cout &lt;&lt; "B = " &lt;&lt; data_ &lt;&lt; '\n';
    }
};

int main()
{
    A a(3);
    C&lt;A&gt; ca(a);
    C&lt;const B&amp;&gt; cb(std::move(ca));
    cb.t_.test();
}
</pre></blockquote>

<p>
To exercise this use case, I've created two client classes <tt>A</tt> and <tt>B</tt>,
and <tt>A</tt> is implicitly convertible to <tt>B</tt>, though not via a
derived-to-base conversion.
</p>

<p>
<tt>C&lt;T&gt;</tt>'s constructor accepts an rvalue <tt>C&lt;U&gt;</tt> where
<tt>U</tt> must be implicitly convertible to <tt>T</tt>.  The constructor uses
<tt>forward</tt>, not <tt>move</tt> so that lvalue reference types can be
held by <tt>C</tt> (though not exercised in this example).
</p>

<p>
Implementations 0, 1 and 3 compile this code (albeit with a warning) and output:
</p>

<blockquote><pre>
B is destructed
</pre></blockquote>

<p>
or
</p>

<blockquote><pre>
B = 0
</pre></blockquote>

<p>
Which both indicate a dangling reference problem.
The reason for this is that the
<tt>static_cast&lt;B&amp;&amp;&gt;(c.t_)</tt> is creating a temporary which
prematurely destructs.
</p>

<p>
Implementations 2, 4 and 5 correctly fail to compile this dangerous code.
</p>

<h2>Summary</h2>

<p>
Six implementations of <tt>forward</tt> have been tested against 6 use cases.
Four of these use cases present safe and useful code.  Two of them illustrate
dangling references.

In the table below, the matrix of implementation vs use
case is compiled.  "pass" means that the implementation compiled and got
the right answer for those use cases which were safe.  For those use cases which
created dangling references, the implementation gets a "pass" if it fails to
compile.  Else an "rfail" is noted which stands for "run time failure".

For those use cases representing useful code, if the implementation failed to
compile it, this is noted with "cfail" (compile time failure) in the table below.
</p>

<ol type="A">
<li>
<b>Should forward an lvalue as an lvalue.</b>
</li>

<li>
<b>Should forward an rvalue as an rvalue.</b>
</li>

<li>
<b>Should <em>not</em> forward an rvalue as an lvalue.</b>
</li>

<li>
<b>Should forward less cv-qualified expressions to more cv-qualified expressions.</b>
</li>

<li>
<b>Should forward expressions of derived type to an accessible, unambiguous base type.</b>
</li>

<li>
<b>Should <em>not</em> forward arbitrary type conversions.</b>
</li>

</ol>

<blockquote>
<table border="1">
<caption>
<tt>forward</tt> implementation results for each use case
</caption>

<tr>
<th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>score</th>
</tr>

<tr>
<th>0</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td align="right">67%</td>
</tr>

<tr>
<th>1</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td align="right">50%</td>
</tr>

<tr>
<th>2</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td align="right">50%</td>
</tr>

<tr>
<th>3</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">rfail</font>&nbsp;</td><td align="right">83%</td>
</tr>

<tr>
<th>4</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;<font color="#C80000">cfail</font>&nbsp;</td><td>&nbsp;pass&nbsp;</td><td align="right">83%</td>
</tr>

<tr>
<th>5</th><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td>&nbsp;pass&nbsp;</td><td align="right">100%</td>
</tr>
</table>
</blockquote>

<p>
Only implementation 5 passes all six tests, and this is what this paper strongly recommends.
It provides readability, flexibility, and safety over the use of <tt>static_cast&lt;T&amp;&amp;&gt;</tt>.
Implementations
0, 1 and 3 (and 0 is a synonym for <tt>static_cast&lt;T&amp;&amp;&gt;</tt>), provide
an opportunity for run time errors which the other implementations catch at compile
time.  Implementations 2 and 4 fail to compile safe and useful use cases.
</p>

<h2>Teachability</h2>

<p>
How do we describe to our customers what (implementation 5) <tt>std::forward</tt> does?
I am not known for great text books educating people on C++.  However below is my
attempt to teach the mechanics of <tt>move</tt> and <tt>forward</tt>.
</p>

<blockquote>
<p>
<tt>std::move(t)</tt> will cast the expression <tt>t</tt> to an rvalue.  One performs
this cast to indicate that you no longer care about the value of <tt>t</tt> after
the expression it is used in.  For example:
</p>

<blockquote><pre>
y = std::move(x); <font color="#C80000">// y now has the value of x, and we no longer care about the value of x</font>
x = new_value();  <font color="#C80000">// because we are about to assign it a new value anyway.</font>
</pre></blockquote>

<p>
<tt>std::forward&lt;T&gt;(u)</tt> is similar to <tt>move(u)</tt> in that it can
be used to cast to an rvalue.  However <tt>forward</tt> has two inputs:  <tt>u</tt>
<em>and</em> <tt>T</tt>.  The input <tt>T</tt> is responsible for telling <tt>forward</tt>
whether to cast <tt>u</tt> to an lvalue, or to an rvalue.  If <tt>T</tt> is an
lvalue reference type, then <tt>u</tt> is cast to an lvalue of that type, else
<tt>u</tt> is cast to an rvalue of that type.  For example:
</p>

<blockquote><pre>
y = std::forward&lt;A&amp;&gt;(x);  <font color="#C80000">// x is copied to y</font>
z = std::forward&lt;A&gt;(x);   <font color="#C80000">// x is moved  to z</font>
</pre></blockquote>

<p>
One typically needs to use <tt>forward</tt> when writing generic code and you
do not know whether the type parameter input to <tt>forward</tt> is going to be
an lvalue reference type or not.  For example:
</p>

<blockquote><pre>
template &lt;class T, class A1&gt;
std::shared_ptr&lt;T&gt;
factory(A1&amp;&amp; a1)
{
    <font color="#C80000">// If A1 is an lvalue reference type,</font>
    <font color="#C80000">//   T's constructor sees an lvalue a1 (and will likely copy from a1).</font>
    <font color="#C80000">//   Else T's constructor sees an rvalue a1 (and will likely move from a1).</font>
    return std::shared_ptr&lt;T&gt;(new T(std::forward&lt;A1&gt;(a1)));
}
</pre></blockquote>

<p>
See chapter X for details on the template argument deduction rules which explain
when <tt>A1</tt> can be deduced as an lvalue reference type.
</p>

<p>
Since there are two inputs to <tt>forward</tt> (<tt>u</tt> and <tt>T</tt>) it is
possible that <tt>u</tt> is not the same type as <tt>T</tt>.  <tt>forward</tt>
restricts the type transformations from <tt>u</tt> to <tt>T</tt> to those which
do not create temporaries and/or lead to dangling reference situations, making
it safer than using <tt>static_cast&lt;T&amp;&amp;&gt;(u)</tt>.
<tt>forward</tt> is also restricted to
those transformations which do not cast away cv-qualifiers.
</p>

<p>
Given:
</p>

<blockquote><pre>
template &lt;class T, class U&gt;
T&amp;&amp;
forward(U&amp;&amp; u);
</pre></blockquote>

<p>
the precise constraints are:
</p>

<ul>
<li>
If <tt>T</tt> is an lvalue reference type, then <tt>U</tt> must also be
an lvalue reference type (meaning an lvalue expression must be passed into
<tt>u</tt> if you are forwarding to an lvalue).
</li>

<li>
Ignoring for a moment any references on the types <tt>T</tt> and <tt>U</tt>,
<tt>U*</tt> must be implicitly convertible to <tt>T*</tt>.
</li>
</ul>

<p>
Don't worry about getting these constraints wrong.  If you make a mistake, it
will be caught at compile time.
</p>

</blockquote>

<h2>Proposed Wording</h2>

<p>
Change [forward]:
</p>

<blockquote>

<pre>
<del>template &lt;class T&gt; T&amp;&amp; forward(typename identity&lt;T&gt;::type&amp;&amp; t);</del>
<ins>template &lt;class T, class U&gt;
  T&amp;&amp;
  forward(U&amp;&amp; u);</ins>
</pre>

<blockquote>
<p>
<del>[<i>Note:</i> The use of <tt>identity</tt> forces users to explicitly specify the
template parameter. This is necessary to get the correct forwarding
semantics. &mdash; <i>end note</i>]</del>
</p>

<p>
<i>Returns:</i> <tt><del>t</del> <ins>static_cast&lt;T&amp;&amp;&gt;(u)</ins></tt>.
</p>

<p>
<ins><i>Remarks:</i> If the following constraints are not met, this signature shall
not participate in overload resolution:</ins>
</p>

<ul>
<li>
<ins>The type formed by <tt>remove_reference&lt;U&gt;::type*</tt> shall be
implicitly convertible to the type <tt>remove_reference&lt;T&gt;::type*</tt>,
and</ins>
</li>
<li>
<ins>if <tt>T</tt> is an lvalue reference type, then <tt>U</tt> shall be an lvalue
reference type.</ins>
</li>
</ul>

<p>
[<i>Example:</i> ...
</p>

</blockquote>

</blockquote>

<h2>Acknowledgements</h2>

<p>
Thanks to Daniel Kr&uuml;gler for a generously provided review.
</p>

</body>
</html>
