2

Possible Duplicate:
Dynamic dispatching of template functions?

I would like to use non-type templates to create grid cells with different memory footprints without having to use dynamically allocated memory on the heap, e.g.

template <int cell_size>
class myCell {...}

There is a finite number of cell sizes (approx. 10), thus I can easily instantiate all of them explicitly. However, which one of the cells are needed is not known at compile time but during runtime only.

I know that templates are a compile-time concept, but is there a way to use templated classes in this way, especially since I can guarantee that all necessary cell types are explicitly instantiated?

Community
  • 1
  • 1

1 Answers1

1

You can use factory pattern, but you'll need a base class as a return type:

template <int cell_size>
class myCell : public cellBase {...}

struct CellFactory
{
   static cellBase* getCell(int cell_size)
   {
      switch (cell_size)
      {
         case 1:
            return new myCell<1>;
            break;
         //and so on
      }
   }
}

This works because you're telling the compiler which specializations it can expect. But I think that a better design exists for the underlying problem you're trying to solve.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • By "better design", do you mean something else than the factory pattern, or something else than using templates? – Michael Schlottke-Lakemper Aug 25 '12 at 14:34
  • @MichaelSchlottke something other than templates. Really depends on the actual problem. – Luchian Grigore Aug 25 '12 at 14:38
  • I thought about using templates, as this would allow the compiler to optimize loops over the internal cell data. As far as I understand C++, if `cell_size` is just a member variable and used to allocate memory on the heap, all loops over the cell data would be execute as-is, since the compiler cannot make any deductions on the best optimization strategy at compile time. – Michael Schlottke-Lakemper Aug 26 '12 at 06:45