문제

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 ?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top