Afficher un message
Vieux 18/10/2007, 20h41   #5
Howard Hinnant
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: std::max(short,long) doesn't work

In article <JWLRi.11899$WX3.90@newsfe5-win.ntli.net>,
Phil Endecott <spam_from_usenet_0606@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:
>
> 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 use it this be forewarned that you should not catch the return
value as a const reference (const long&), but catch it as a long
instead. If you catch it as a reference:

const long& m = std::max<long>(s,l);

then you risk having a reference to a destructed temporary (the
temporary long created from converting from s).

Here is a more robust (and more flexible) min/max which does not have
this danger, and is usable without specifying <long>:

http://www.open-std.org/jtc1/sc22/wg...007/n2199.html

The std committee briefly considered this solution for standardization
in C++0X but rejected it. However the reference implementation is there
in the paper free for the taking.

-Howard
  Réponse avec citation
 
Page generated in 0,06843 seconds with 9 queries