Re: std::max(short,long) doesn't work
On Oct 18, 9:34 pm, Phil Endecott <spam_from_usenet_0...@chezphil.org>
wrote:
> Hi Neelesh, thanks for the quick reply.
>
> Neelesh Bodas wrote:
> > On Oct 18, 9:19 pm, Phil Endecott <spam_from_usenet_0...@chezphil.org>
> > wrote:
> >> Dear Experts,
>
> >> I'm surprised to find that std::max doesn't work (i.e. won't compile) if
> >> the arguments are not of exactly the same type, e.g. one is a short and
> >> the other is a long:
>
> > thats because the template is defined to take two arguments of same
> > type
>
> Indeed, but I'm surpised that the short isn't promoted to a long as it
> would be for a non-template function where both arguments have the same
> type:
>
14.8.1(4) from the standard:
"Implicit conversions will be performed on a function argument to
convert it to the type of the corresponding function parameter if the
parameter type contains no template parameters
that participate in template argument deduction"
In the current case since both s and l participate in template
argument deduction, s won't be promoted to the type of l.
> int f(long x, long y) {
> return 1;
>
> }
>
> int g() {
> short s;
> long l;
> return f(s,l);
>
> }
>
> I'm not saying that anything is wrong - this just wasn't what I had
> (naively) expected.
>
> > Yes you can, just explicitly provide template arguments:
> > std::max<long>(s,l);
>
> Ah, that's interesting. So if I provide an explicit type then it
> behaves like my non-template function f above.
If you provide the explicit type, then s and l are no more used in
template argument deduction. Hence s can be safely promoted to the
desired type (long in this case).
As another example, this will also work: std::max<int>(s,l); . In this
case, both s and l will undergo standard conversion to int. This is
possible since neither of them participate in template argument
deduction.
-N
|