How does the compile choose which template function to call?
<p>Regarding the below code, how does the compiler choose which template function to call?
If the const T&amp; function is omitted, the T&amp; function is always called.
If the T&amp; function is omitted, the const T&amp; function is always called.
If both are included, the results are as below.</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;typeinfo&gt;

template &lt;typename T&gt;
void function(const T &amp;t)
{
    std::cout &lt;&lt; "function&lt;" &lt;&lt; typeid(T).name() &lt;&lt; "&gt;(const T&amp;) called with t = " &lt;&lt; t &lt;&lt; std::endl;
}

template &lt;typename T&gt;
void function(T &amp;t)
{
    std::cout &lt;&lt; "function&lt;" &lt;&lt; typeid(T).name() &lt;&lt; "&gt;(T&amp;) called with t = " &lt;&lt; t &lt;&lt; std::endl;
}

int main()
{
    int i1 = 57;
    const int i2 = -6;

    int *pi1 = &amp;i1;
    int *const pi3 = &amp;i1;
    const int *pi2 = &amp;i2;
    const int *const pi4 = &amp;i2;

    function(pi1); ///just a normal pointer -&gt; T&amp;
    function(pi2); ///cannot change what we point to -&gt; T&amp;
    function(pi3); ///cannot change where we point -&gt; const T&amp;
    function(pi4); ///cannot change everything -&gt; const T&amp;

    return 0;
}

/* g++ output: 
function&lt;Pi&gt;(T&amp;) called with t = 0x22cd24
function&lt;PKi&gt;(T&amp;) called with t = 0x22cd20
function&lt;Pi&gt;(const T&amp;) called with t = 0x22cd24
function&lt;PKi&gt;(const T&amp;) called with t = 0x22cd20
*/

/* bcc32 output: 
function&lt;int *&gt;(T&amp;) called with t = 0012FF50
function&lt;const int *&gt;(T&amp;) called with t = 0012FF4C
function&lt;int *&gt;(const T&amp;) called with t = 0012FF50
function&lt;const int *&gt;(const T&amp;) called with t = 0012FF4C
*/

/* cl output: 
function&lt;int *&gt;(T&amp;) called with t = 0012FF34
function&lt;int const *&gt;(T&amp;) called with t = 0012FF28
function&lt;int *&gt;(const T&amp;) called with t = 0012FF34
function&lt;int const *&gt;(const T&amp;) called with t = 0012FF28
*/
</code></pre>
