Search code examples
c++stlsgi

A template function and a non-template overload of this function, which is a best match?


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.


Solution

  • 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.