Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map two types at compile time

I have a set of types related with a one-to-one relation, for example:

TypeA ---> Type1
TypeB ---> Type2 
TypeC ---> Type3

I know these relation at compile time.

Then, I have a template class that depends on this two types:

template<class T1,class T2>
class MyClass
{
  T1 foo;
  T2 bar;
};

Now, the user of my library will type something like:

MyClass<TypeA,Type1> x;

This is inconvenient because there is a dependency between the two types and it should be enough for the user specify only the first type.

Also, mixing the two types shouldn't be possible:

MyClass<TypeA,Type2> y; //it should not compile

I am not very familiar with template meta programming, I got the impression that this is doable task, but I may be wrong.

The number of types involved is big, however I am happy to run a script to generate the code if necessary.

Do you know if it is possible or I am wasting my time? Do you have any ideas to point me on the right direction?

like image 483
Alessandro Teruzzi Avatar asked Oct 12 '11 12:10

Alessandro Teruzzi


2 Answers

template<class T>
struct get_mapped;

template<>
struct get_mapped<TypeA>{
    typedef Type1 type;
};

// and so on....


template<class T>
class MyClass{
    typedef typename get_mapped<T>::type T2;

    T foo;
    T2 bar;
};
like image 138
Xeo Avatar answered Oct 01 '22 23:10

Xeo


template<class T> struct TypeLetter2TypeDigit;

template<> struct TypeLetter2TypeDigit<TypeA> { typedef Type1 type; };
template<> struct TypeLetter2TypeDigit<TypeB> { typedef Type2 type; };
template<> struct TypeLetter2TypeDigit<TypeC> { typedef Type3 type; };


template<class T1>  // Type2 is not needed
class MyClass 
{ 
  // Type2 is deduced.
  typedef typename TypeLetter2TypeDigit<T1>::type T2;
  T1 foo; 
  T2 bar; 
}; 
like image 35
Alexey Malistov Avatar answered Oct 01 '22 22:10

Alexey Malistov