Reputation: 4770
The code is as follows:
template <class InputIterator, class OutputIterator>
inline OutputIterator copy(InputIterator first, InputIterator last,
OutputIterator result)
{
return __copy_dispatch<InputIterator,OutputIterator>()(first, last, result);
}
//A overload version
inline char* copy(const char* first, const char* last, char* result) {
memmove(result, first, last - first);
return result + (last - first);
}
If I call copy(int*, int*)
, which is the best match, will the compiler instantiate a new function use int*
as the template parameter, or int*
will be convert to char*
.
And what if I call copy(char[], char[])
notice I just use char[]
to note the type of parameters.
Upvotes: 2
Views: 446
Reputation: 23610
Since int *
is not implicitly convertible to char *
nor to const char *
, the template function will be called. Removing the template function would result in compile time error.
Suggestion: There is great value in playing around with the compiler yourself. You can add lines like
std::cout << "template function called.\n";
into your overloads or use the debugger to do that kind of stuff. It's a great learning experience. You might also simply read some C++ books for an introduction.
Upvotes: 4
Reputation: 227418
if I call copy(int*, int*), which is the best match,
There in only one match: the template. The version taking const char*
does not match at all.
And what if I call copy(char[], char[])
again, the template wins, because the arguments are not const
. If you did this:
const char* c1 = ....;
const char* c2 = ....;
copy(c1, c2);
then the non-template would win, because in the case of a perfect overload match, a non-template function takes precedence.
Upvotes: 1