Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May I use a constant number to choose a class at compile time, possibly using templates?

Let's say I have a constant value (possibly of some enum type). Let's say I have many classes A, B, D, etc.

Can I have something like this?

C<1> anInstanceOfA; //This will be of type A
C<2> anInstanceOfB; //This will be of type B
C<3> anInstanceOfD; //This will be of type D

So, is it possible to select a class based on a constant number at compile time?

The general problem is that I am trying to select a functor based on a table, in which the index is an enum. I would like to avoid polymorfism if possible.

Edit: For this project I cannot use C++11, thanks anyway to who answered in that context, very interesting to know anyway.
Edit 2: In general I can have more than 2 target classes, I have edited my question

like image 355
Antonio Avatar asked Jul 30 '13 14:07

Antonio


2 Answers

This isn't the only way to do this, but I hope acceptable for your purposes:

struct A { };
struct B { };

template <int N>
struct choices;

template <>
struct choices<1> { typedef A type; };

template <>
struct choices<2> { typedef B type; };

template <int N>
using C = typename choices<N>::type;

Update: To do the same without C++11 features, you should make C a class with a typedef member type equal to the corresponding type alias above:

template <int N>
struct C
{
    typedef typename choices<N>::type type;
};

// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
like image 159
David G Avatar answered Nov 15 '22 07:11

David G


Using the LSP and plain C++98:

template <int N> class C;
template <> class C<1> : public A {};
template <> class C<2> : public B {};
template <> class C<3> : public D {};

C<1> anInstanceOfA;

Since public inheritance in C++ satisfies the IS-A rule, anInstanceOfA both IS-A C<1> object and IS_AN A object.

like image 25
MSalters Avatar answered Nov 15 '22 07:11

MSalters