Boost logo

Boost :

From: Ullrich Koethe (koethe_at_[hidden])
Date: 2001-03-29 11:25:52


Another very important aspect (that has no counterpart in pure math) is
type promotion. For example, Jeremy's list says:

  a + b Convertible to X and models Additive Abelian Group.

I think we must be more specific about the type of the result. There are
clear rules for promotion of the built-in types, for example

short + short => int
double * short => double

These rules must be formulated in promotion_traits (invented by Todd
Veldhuizen) so that

* the rules for new numeric types can be derived
  from the rules for its constituents.
* templated algorithms can select appropriate types for
  results and intermediate variables

In my VIGRA library, I distinguish two promotion types:

- if X is any algebraic type, then

  X op X => NumericTraits<X>::Promote
  (e.g. NumericTraits<short>::Promote is int)

- if {G, R} is an R-Module, then

  G op R => PromoteTraits<G, R>::Promote
  (e.g. PromoteTraits<short, double>::Promote is double)

In addition, there are conversion functions

NumericTraits<T>::fromPromote() and
PromoteTraits<T,U>::firstFromPromote()

that transform back to the original type, including necessary round-off
and clipping at the domain borders. (Actually, it's slightly different,
but you get the idea)

Now I can do:

template <class T, class U>
struct PromoteTraits<RGBValue<T>, RGBValue<U> >
{
    typedef RGBValue<typename PromoteTraits<T, U>::Promote> Promote;
};

and

template <class T, class U>
typename PromoteTraits<RGBValue<T>, RGBValue<U> >::Promote
operator+(RGBValue<T> l, RGBValue<U> r)
{
    typename PromoteTraits<RGBValue<T>, RGBValue<U> >::Promote res(l);
    res += r;
    return res;
}

I've found this to be a very useful method which I need every day.

Ulli

-- 
 ________________________________________________________________
|                                                                |
| Ullrich Koethe  Universität Hamburg / University of Hamburg    |
|                 FB Informatik / Dept. of Computer Science      |
|                 AB Kognitive Systeme / Cognitive Systems Group |
|                                                                |
| Phone: +49 (0)40 42883-2573                Vogt-Koelln-Str. 30 |
| Fax:   +49 (0)40 42883-2572                D - 22527 Hamburg   |
| Email: u.koethe_at_[hidden]               Germany             |
|        koethe_at_[hidden]                        |
| WWW:   http://kogs-www.informatik.uni-hamburg.de/~koethe/      |
|________________________________________________________________|

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk