tags:

views:

79

answers:

1

Hi, I need to store types in a list with one identifier for each one;

I need a random access to the elements of the list without knowing the identifier at compilation time

I tried the meta-programming typelist but I don't know how to return types with the identifier, i get compilation error :

'cannot appear in a constant-expression'
A: 

Here is an idea for you:

  1. Create sequence of types supporting random access (boost::mpl::vector will fit)
  2. Each element in a sequence will have its unique identifier, which its position (0, 1, 2...)
  3. Create a template analog of virtual table with functions accepting a predicate that has an operator overloaded for each type in a list. This template should be instantiated for each predicate. For example, function at index 0 will call a “Predicate::operator<Type1>()” etc. Use recursive template instantiation to initialize that table.

So, to get a unique identifier in compile-time, use something like:

boost::mpl::find<type_list, T>::type::pos::value

To get a type for a given identifier at compile-time:

boost::mpl::at_c<type_list, which /* unsigned int known at compile-time */>::type

To get a type at run-time using a number, create a functor with all possible overloads:

struct Visitor {
  template <typename T>
  void operator () ();
};

template <>
void operator ()<Type1> ();

template <>
void operator ()<TypeN> ();

And invoke it using instantiation of the virtual table analog described in p.3, something like:

void applyVisitor (int index, Visitor & v) {
    DispatchTable<Visitor>::functions[ index].call (v);
}

The idea is simple, but generic implementation is a bit tricky. It took me 377 lines of code to implement.

Vlad Lazarenko