1

C defines various rules regarding integer promotion, here's a great answer describing how this works.

In GCC you can do this:

#define max(a,b) \
   ({ __typeof__ (a) _a = (a); \
       __typeof__ (b) _b = (b); \
     _a > _b ? _a : _b; })

Which will evaluate to the maximum value of the type determined by the C rules as above.

In using std::min or std::max using mixed types, it's necessary to provide the appropriate type to cast to as a template parameter:

size_t const subcount = std::min<Offset>(count, treecap - offset);

To get a min/max that evaluates to the type as per the C integer promotion rules, it would be necessary to know how the types relate, and what the resultant type would be, for every combination of left and right input types.

I wish to perform a min/max, with the same behaviour as the C sample under GCC given above, and with the same promotion (thereby ensuring the same behaviour as in GCC). How can I do this in C++ and/or MSVC?

Note that immediately after performing this "natural" min/max, I'll be numeric_casting to the expected size range.

Community
  • 1
  • 1
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526

1 Answers1

1

There's a very good implementation here that I've used for various projects: http://www.oonumerics.org/blitz/traits.html

rcv
  • 6,078
  • 9
  • 43
  • 63
  • 1
    A shame this isn't part of standard C++, but it hardly surprises me. C++ can't make its mind up about compatbility with C and lives in a nasty no mans land. – Matt Joiner Nov 07 '10 at 06:39