2

I have defined such function:

template<typename T>
void SwapMe(T *first, T *second)
{
    T tmp = *first;
    *first = *second;
    *second = tmp;
}

Then using it like so:

SwapMe(&data[i], &data[j]);

As you see, I'm not using explicitly SwapMe<T>(...); but it does work!
Why C++ standard allows to avoid explicitly specifying the type of the arguments ?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Secret
  • 2,627
  • 7
  • 32
  • 46
  • STL includes this as part of [his series](http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-2-of-n). – chris Jan 23 '13 at 04:07
  • 1
    Oleg, this is called Template argument deduction. I'd suggest you take a look at some good [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) for starters. –  Jan 23 '13 at 04:08

1 Answers1

5

The necessary T can be deduced from the type of *first.

Explicitly specifying by programmer is only necessary if the deduction cannot be automatically made by the compiler.

This (seemingly simple but actually quite involved) phenomenon is known as Argument Dependent Name Lookup or Koenig lookup, named after its inventor Andrew Koenig.

Arun
  • 19,750
  • 10
  • 51
  • 60