Why does this code call another template function in vs2005?

The code:

#include <iostream>
using namespace std;

// compares two objects
template <typename T> void compare(const T&, const T&){
    cout<<"T"<<endl;
};
// compares elements in two sequences
template <class U, class V> void compare(U, U, V){
    cout<<"UV"<<endl;
};
// plain functions to handle C-style character strings
void compare(const char*, const char*){
    cout<<"ordinary"<<endl;
};

int main() {

    cout<<"-------------------------char* --------------------------"<< endl;

    char* c="a";
    char* d="b";
    compare(c,d);

cout<<"------------------------- char [2]---------------------------"<< endl;

    char e[]= "a";
    char f[]="b";
    compare(e,f);

    system("pause");
}

Result:

------------------------- char * ------------------ ----- ---

T

------------------------- char [2] ---------------- ----- -

ordinary

And my question is: Why does the comparison (c, d) cause the comparison (const T &, const T &) and the comparison (e, f) call the usual function, even if the arguments of two functions: char * s?

+5
source share
1 answer

It seems that VS2005 may erroneously process variables eand fboth types const char *.

Consider the following code:

#include <iostream>
using namespace std;

template <typename T> void compare (const T&, const T&) {
    cout << "T:        ";
};

template <class U, class V> void compare (U, U, V) {
    cout << "UV:       ";
};

void compare (const char*, const char*) {
    cout << "ordinary: ";
};

int main (void) {
    char* c = "a";
    char* d = "b";
    compare (c,d);
    cout << "<- char *\n";

    char e[] = "a";
    char f[] = "b";
    compare (e,f);
    cout << "<- char []\n";

    const char g[] = "a";
    const char h[] = "b";
    compare (g,h);
    cout << "<- const char []\n";

    return 0;
}

which outputs:

T:        <- char *
T:        <- char []
ordinary: <- const char []

13.3 Overload resolution ++ 03 ( ++ 11 , ) , , , ( ) , , .

, - , ( - /, () , ..).

.

(. 13.3.3 Best viable function ++ 03).

, "" , , . - , .

, , .

, , , , .

"" "". , , , .

Rank                 Conversion
----                 ----------
Exact match          No conversions required
                     Lvalue-to-rvalue conversion
                     Array-to-pointer conversion
                     Function-to-pointer conversion
                     Qualification conversion
Promotion            Integral promotions
                     Floating point promotions
Conversion           Integral conversion
                     Floating point conversions
                     Floating-integral conversions
                     Pointer conversions
                     Pointer-to-member conversions
                     Boolean conversions

, F1 F2 (, ), F1 , :

F1 - , F2 - .


, , , - , , .

: 13.3.3.2 Ranking implicit conversion sequences. , , , :

S1 , S2, (1) S1 S2 ( , 13.3.3.1.1, Lvalue; , )...

( ) ( ), .

, . - , , , , ).

+4

All Articles