Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create template dependent member type

I am trying to cut down and simplify some horribly nested and over specialized templated C++ code. To do so, I would like to be able to declare member type which is dependent on the templated type that the function or class has been instantiated with.

Take the following generic class template the resulting template specializations. The type of 'a' depends on the instantiation type.

  template <typename Float> class A;

  template <>
    class A<double> {  
      double a;
    }
  };

  template <>
    class A<float> {  
      float a;
    }
  };


  template <>
    class A<short> {  
      float a;
    }
  };

The classes are identical except for the type of 'a', the mapping of template type to type of being double->double, float->float and short->float. Is there a way simply encapsulated this mapping to allow to only write the class once?

I guess I would like to be write something like the following, but I have no idea if something this is possible.

  typedef double Float2<double>;
  typedef float Float2<float>;
  typedef float Float2<short>;

  template <typename Float>
    class A {  
      Float2<Float> a;
    }
  };

Note I am using C++03 and cannot use C++11 for this purpose (I think decltype may be of use here, but I'm not sure).

like image 560
Maddy Scientist Avatar asked Feb 16 '23 12:02

Maddy Scientist


1 Answers

There's no need to use decltype. You can just create a type trait and specialize it to provide the appropriate type mappings:

template<typename>
struct mapper;

template<>
struct mapper<double> {
    typedef double type;
};

template<>
struct mapper<float> {
    typedef float type;
};

template<>
struct mapper<short> {
    typedef float type;
};

template <typename Float> 
class A {
    typedef typename mapper<Float>::type float_type;

    float_type a;
};
like image 57
mfontanini Avatar answered Feb 23 '23 23:02

mfontanini