Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to create an automatic casting map?

Say we have library A which contains two classes of objects C1 and C2.

For every element in C1 there is a compatible element in C2.

Say we want to create a generic function that converts from one onto the other.

template<typename C1, typename C2> 
C2 SpecialCast(C1 c1) {
     /* do some generic work */
}

This requires us to always write SpecialCast<Type>(parameter) However this is redundant, because all that;s needed to know the casting type is to know the parameter type. So this is adding unnecessary verbosity to the code.

And ideal solution would be to define a header table of the vallid type conversions such that one could do:

template<typename C1> 
C2 SpecialCast(C1 c1) {
     /*get C2 from C1 using the table*/
     /* do some generic work */
}

But I am currently struggling with finding a good way to define the table in the simplest possible way.

like image 685
Makogan Avatar asked Aug 11 '19 18:08

Makogan


2 Answers

Use a helper class to define the corresponding type. Let's say the library has classes A1, A2, and A3, that get casted to B1, B2, and B3. Ok, then:

template<typename T> struct type_map;

template<> struct type_map<A1> {

   typedef B1 type_t;
};

template<> struct type_map<A2> {

   typedef B2 type_t;
};

template<> struct type_map<A3> {

   typedef B3 type_t;
};

Now, SpecialCast can be defined simply as

template<typename T> 
typename type_map<T>::type_t SpecialCast(T t) {
     /* do some generic work */
}
like image 52
Sam Varshavchik Avatar answered Nov 07 '22 10:11

Sam Varshavchik


You can just use good old function overloading:

template <class T1, class T2>
T1 SpecialCast(T2)
{
    // ...
}

C1 SpecialCast(C2 c2)
{
    return SpecialCast<C1>(c2);
}

C2 SpecialCast(C1 c1)
{
    return SpecialCast<C2>(c1);
}
like image 28
Nikos C. Avatar answered Nov 07 '22 10:11

Nikos C.