Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top