简体   繁体   中英

C++ templates implicitly use

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM