|
Boost : |
From: Andrei Alexandrescu (See Website For Email) (SeeWebsiteForEmail_at_[hidden])
Date: 2005-05-02 23:49:31
Edward Diener wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
>> By the way, it was FOREACH that inspired me to figure out a simple
>> solution to max, which then Eric improved. It's basically like this:
>>
>> #define max(a, b) (max_fn(true ? (a) : (b), false ? (a) : (b)))
>>
>> which presto, nice-o passes the appropriate types to a template max_fn
>> function that now can be smart about returning lvalues and so on.
>
>
> You have stumped me here. Why does one not do:
>
> #define max(a, b) (max_fn((a),(b))
>
> instead ?
I thought nobody's gonna ask :o).
The problem on the former code is that it puts a lot of aggravation on
max_fn as far as deducing the proper type returned; see
http://moderncppdesign.com/publications/cuj-04-2001.html for a
discussion on why.
On the contrary, the trick (used also, and inspired from, FOREACH):
#define max(a, b) (max_fn(true ? (a) : (b), false ? (a) : (b)))
lets the ?:'s rules figure out that type; now max_fn has two arguments
of the same type, and can much more easily figure out what to return
(only needs to deal with const and rvalues, stuff that was piece of cake
for Eric to figure out).
Andrei
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk