Re: std::max(short,long) doesn't work
* Howard Hinnant:
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).
Possibly you meant something other than what you actually wrote.
std::max returns the same type as the argument type.
Therefore, in the example above it returns a 'long', not a 'long const&'.
Therefore, the reference is not bound to an internal temporary in the
call, but to a temporary that the compiler creates for just this
purpose. And that temporary's life is extended to the end of the scope
of the reference. It's all very safe.
Are you by any chance referring to the reference implementation you link
to below?
I'm too lazy to check... :-)
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/wg21/docs/papers/2007/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.
Cheers,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?