How to create a member member template type

I am trying to cut and simplify some terribly nested and more specialized C ++ boilerplate code. To do this, I would like to be able to declare a member type, which depends on the template type with which this function or class was created.

Take the following general class template template as a result of creating custom templates. Type "a" depends on the type of instance.

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 'a', matching the type of the template with the type double-> double, float-> float and short-> float. Is there a way to just encapsulate this mapping so that I can only write the class once?

I think I would like to write something like the following, but I have no idea if something like 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 the decltype method can be used here, but I'm not sure).

+4
source share
1 answer

No need to use decltype . You can simply create a type trait and specialize in providing matching types of 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; }; 
+8
source

Source: https://habr.com/ru/post/1481482/


All Articles