How does the compile choose which template function to call?

Posted by aCuria on Stack Overflow See other posts from Stack Overflow or by aCuria
Published on 2010-04-25T16:36:44Z Indexed on 2010/04/25 16:43 UTC
Read the original article Hit count: 259

Filed under:

Regarding the below code, how does the compiler choose which template function to call? If the const T& function is omitted, the T& function is always called. If the T& function is omitted, the const T& function is always called. If both are included, the results are as below.

#include <iostream>
#include <typeinfo>

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

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

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

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

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

    return 0;
}

/* g++ output: 
function<Pi>(T&) called with t = 0x22cd24
function<PKi>(T&) called with t = 0x22cd20
function<Pi>(const T&) called with t = 0x22cd24
function<PKi>(const T&) called with t = 0x22cd20
*/

/* bcc32 output: 
function<int *>(T&) called with t = 0012FF50
function<const int *>(T&) called with t = 0012FF4C
function<int *>(const T&) called with t = 0012FF50
function<const int *>(const T&) called with t = 0012FF4C
*/

/* cl output: 
function<int *>(T&) called with t = 0012FF34
function<int const *>(T&) called with t = 0012FF28
function<int *>(const T&) called with t = 0012FF34
function<int const *>(const T&) called with t = 0012FF28
*/

© Stack Overflow or respective owner

Related posts about c++