Boost logo

Boost :

From: k.hagan_at_[hidden]
Date: 2001-05-01 04:10:49


I wrote:

> I'm losing track of what has and hasn't been suggested. Have we
> considered specialising a class template with a static member?
>
> template<class T> class math
> {
> static T const pi;
> };

Paul Bristow replied:

> I don't think this has been suggested previously, but I am unclear
> exactly how this works. Can you provide a fuller example please?

I meant something like this...

   template<class T> class math { static T const pi; };
 // single precision
   template<> class math<float> { static float const pi; };
   float const math<float>::pi = 3.14f;
 // double precision
   template<> class math<double> { static double const pi; };
   double const math<double>::pi = 3.14;

...but looking around for an example to check the syntax, I find that
the numeric_limits template uses inline functions for all non-integer
constants. (Those Fermilab users will be upset.) Ed raised other
problems -- namely that the linker may be unable to discard the
global variables and the compiler may be unable to do constant
folding. I don't know if these constraints come from the language or
are "mere" quality of implementation issues.

Another idea (which I'll toss into the pot for fun) is one class per
constant, with implicit conversions.

   struct pi_constant
   {
   #ifdef <compiler can hack a member template>
      template<class T> operator T() const;
   #else
      operator float() const { return 3.14f; }
      operator double() const { return 3.14; }
   #endif
   };
   extern pi_constant const pi;

I've seen this suggested as a way of defining a "NULL keyword". It
has the advantage that end-users do indeed write "boost::pi" but
enjoy the benefits of inlining and hopefully constant folding.

I think it has two main problems. Firstly the template member, which
we would need to keep the architecture open for arbitrary types, is
not something that all current compilers like. Secondly, it is not
hard to imagine contexts where simply writing "pi" leads to ambiguity
and the Fermilab users would have to learn that sometimes they need
to write an explicit conversion.

Since, as I've remarked, the idiom has already been used for
a "NULL", there may be people out there with more experience than I
who can point out other problems. (I'm using MSVC, and the template
conversion operator is too much for it.)


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