Boost logo

Boost Users :

Subject: Re: [Boost-users] boost concept to make int template parameter available at runtime?
From: Christopher Jefferson (chris_at_[hidden])
Date: 2009-09-17 03:31:29


On 17 Sep 2009, at 08:00, Sebastian Weber wrote:

> Hi!
>
> I am wondering if some boost library (like fusion) or similar may
> help me
> solve an awkward problem. In principle I have a class which has an int
> template parameter, for example:
>
> template <int VAL>
> class A {
> void print_val() {
> std::cout << "my value is " << VAL << std::endl;
> }
> };
>
> Now I want to make the parameter VAL of class A available at runtime
> (of
> course only a limited range, but still), like this
>
> class Aruntime {
>
> void set_val(int v) { val = v; }
> int val;
>
> ... and again same stuff from A<val> ...
>
> };
>
> I am sure there is an easy solution to it. One solution would be to
> use an
> object factory, I guess. There I would register for each integer the
> respective class A which I had to wrap into some other class in
> order to get
> rid of the template parameter and virtualize the print_val function.
> This
> may not be a boost-problem directly, but any help would be great.

I'm not sure if this is completely a solution, but it's how I deal
with a similar problem.

Change class A so it accepts as a template parameter just "T t", and
then you pass it ints at runtime, and any int you pass will produce
the same value.

You then construct a new class (something similar to this is almost
certainly in MPL, and fusion, and everything similar, but just for
this class it's probably worth writing your own:

template<int i>
struct compiletime_int
{
   operator int()
   { return i; }
};

Now if you compile A<compiletime_int<2> >, and use optimisation, you
will find your code is as optimised as your original 'A' class was.
The only limitation of this technique is that it can only be used when
you don't need the parameter to act like a compile-time constant (for
example, if you want to use it as the size of a C array, or a
std::array).

Chris


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net