質問

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