Boost logo

Boost :

From: Ross Smith (r-smith_at_[hidden])
Date: 2001-10-25 19:49:36


As long as we're all piling on, here's yet another suggestion...

namespace boost {

  // First, a couple of generic templates...

  template <typename Tag, typename Result> struct make_constant {
    static Result get() {
      return static_cast<Result>(Tag::get());
    }
  };

  template <typename Tag> struct constant {
    template <typename Result> operator Result() const {
      return make_constant<Tag, Result>::get();
    }
  };

  // Example of a specific constant...

  struct pi: public constant<pi> {
    static double get() {
      return 3.141592653589793;
    }
  };

  // ...for which we specialise make_constant for float and long double

  template <> struct make_constant<pi, float> {
    static float get() {
      return 3.14159265f;
    };
  };

  template <> struct make_constant<pi, long double> {
    static long double get() {
      return 3.14159265358979323846264L;
    };
  };

}

Now we can use boost::pi() as a constant, and the type will be deduced
from the context. If the context gives the wrong type or is ambiguous,
just use an explicit cast. (This doesn't quite solve the "people who
want to use 'pi' unadorned" problem, but I think a simple pair of
parentheses should be acceptable.)

When the type is float or long double, the values given for each type
above will be used. For any other type, the generic version of
make_constant will come into play, and the value will be converted from
double (with a compile-time error if no such conversion exists).

Users can easily add their own constants, in their own namespace but
with the same features, by providing the equivalent of struct pi above
(deriving it from boost::constant<itself>), with a get() function that
provides a standard value (note that the return type of get() doesn't
have to be double), and specialisations of boost::make_constant for any
result types for which the default conversion isn't desired. Since one
of the template arguments to these specialisations is in the user's
namespace, there's no danger of collision with future additions to the
boost constants.

-- 
Ross Smith ...................................... Auckland, New Zealand
r-smith_at_[hidden] ........................ http;//halflife.mani.ac.nz/
        "A wise man learns from the mistakes of others; a fool
        learns only from his own."     -- Gen. Aleksandr Lebed

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