template <class T>
void swap(T &t1, T &t2)
{
T tmp = t1;
t1 = t2;
t2 = tmp;
}
template <class Bi>
void reverse(Bi begin, Bi end)
{
while (begin != end) {
--end;
if (begin != end) {
::swap(*begin++, *end);
}
}
}
Why does the above work?
template <class Bi, class T>
void reverse2(Bi begin, Bi end)
{
while (begin != end) {
--end;
if (begin != end) {
T tmp = *begin;
*begin++ = *end;
*end = tmp;
}
}
}
While this doesn’t?
For the first example to work, the compiler has to be able to deduce the argument types of the swap function at compile time. (I.e. it has to be able to determine the types of *begin++ and *end.) If this is possible, why can’t the compiler deduce the type of the value returned by *begin in the second example and choose T accordingly?
The compiler deduces the argument types from the function signature, not the function body.
As
Tis not used in the function signature at all (void reverse2(Bi begin, Bi end)), the compiler can not deduce the type. However, in the case ofswapit can deduce the type, because it was deduced in the function signature.