Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code call different template function in vs2005?

Tags:

c++

The code is:

#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");
}

The result is:

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

T

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

ordinary

And my question is: Why does compare(c,d) call compare(const T&, const T&) and compare(e,f) call the ordinary function even though the arguments of the two functions are char*s?

like image 691
hu wang Avatar asked Oct 08 '22 01:10

hu wang


1 Answers

It appears that VS2005 may be erroneously treating the e and f variables as const char * types.

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 []

Section 13.3 Overload resolution of C++03 (section numbers appear to be unchanged in C++11 so the same comments apply there) specifies how to select which function is used and I'll try to explain it in (relatively) simple terms, given that the standard is rather a dry read.

Basically, a list of candidate functions is built based on how the function is actually being called (as a member function of an class/object, regular (unadorned) function calls, calls via a pointer and so on).

Then, out of those, a list of viable functions is extracted based on argument counts.

Then, from the viable functions, the best fit function is selected based on the idea of a minimal implicit conversion sequence (see 13.3.3 Best viable function of C++03).

In essence, there is a "cost" for selecting a function from the viable list that is set based on the implicit conversions required for each argument. The cost of selecting the function is the sum of the costs for each individual argument to that function, and the compiler will chose the function with the minimal cost.

If two functions are found with the same cost, the standard states the the compiler should treat it as an error.

So, if you have a function where an implicit conversion happens to one argument, it will be preferred over one where two arguments have to be converted in that same way.

The "cost" can be see in the table below in the Rank column. An exact match has less cost than promotion, which has less cost than conversion.

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

In places where the conversion cost is identical for functions F1 and F2 (such as in your case), F1 is considered better if:

F1 is a non-template function and F2 is a function template specialization.


However, that's not the whole story since the template code and non-template code are all exact matches hence you would expect to see the non-template function called in all cases rather than just the third.

That's covered further on in the standard: The answer lies in section 13.3.3.2 Ranking implicit conversion sequences. That section states that an identical rank would result in ambiguity except under certain conditions, one of which is:

Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if (1) S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form defined by 13.3.3.1.1, excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) ...

The conversions for the template version are actually a proper subset (qualification conversion) of the non-template version (qualification AND array-to-pointer conversions), and proper subsets are deemed to have a lower cost.

Hence it prefers the template version in the first two cases. In the third case, the only conversions are array-to-pointer for the non-template version and qualification for the template version, hence there's no subset in either direction, and it prefers the non-template version based on the rule I mentioned above, under the ranking table).

like image 89
paxdiablo Avatar answered Oct 13 '22 12:10

paxdiablo