Tianyi
Tianyi

Reputation: 197

Template and function Overloading

To study the Overloading of Function Templates, I have wrote two functions:

template <typename T>
void pe16_61_compare(const T&, const T&) {
    cout <<"template pe16_61_compare(T, T) called" << endl;
}

// plain functions to handle C-style character strings
void pe16_61_compare(const char*, const char*) {
    cout <<"normal func pe16_61_compare(...) called" << endl;;
}

and then I have defined some variables and called the function: pe16_61_compare

const char const_arr1[] = "world", const_arr2[] = "hi";
char ch_arr1[] = "world";
// first call
pe16_61_compare(ch_arr1, const_arr1);
// second call
pe16_61_compare(const_arr1, const_arr2);

the output result is:

template pe16_61_compare(T, T) called
normal func pe16_61_compare(...) called

What confuse me is that the first call invoke the template function. For me, for the first call, both two pe16_61_compare function are viable functions and the have the same rank of conversion (non-const to const and array to pointer), and it is said in this case, the template function should be removed from the set of viable functions.

Could any one tell me why? Thank you for considering my question!

Upvotes: 3

Views: 152

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477494

For the first call, T = char[6] is a better match than the conversion to char const *, so the template wins.

For the second call, no single template parameter can work for arrays, so the non-template overload is the only matching one.

If you say,

pe16_61_compare(static_cast<char const *>(const_arr_1),
                static_cast<char const *>(const_arr_2));

then both the template instance and the ordinary function are viable and have the same signature, but as a tie breaker the non-template function wins (i.e. this isn't ambiguous).

Upvotes: 3

Related Questions