Search code examples
c++templatesfactory-pattern

factory for product templates


I'm writing my own implementation of hash_table (just for fun). I would like to implement a series of hashing routines and give the user a chance to pick one with an ID. For that I would like to use a factory which would produce appropriate hasher. The hashers are class templates. Is it possible to write a factory for product templates without using anything like typelists to specify every possible type provided ? I'm most concerned about product registration.

More general. My products are:

template <typename X>
class i_prod
{
};

template <typename X>
class c_prod_a : public i_prod {

};

template <typename X>
class c_prod_b : public i_prod {

};

The factory is also a class template. But how to sort out the registration process ?


Solution

  • Yes, use a traits class template with the id as the template argument. To register an id, you specialize the traits class, which can be done distributively. You can use enum or an integral type for the id, but that makes collisions hard to avoid.

    Instead you can use tag structs that just act as identifiers, like iterator tags.

    This can all be resolved at compile tine.