Templates conditional type

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • buchtak
    New Member
    • Mar 2009
    • 4

    Templates conditional type

    Hi,

    can I define type of a variable based on some other type using templates? For example I have

    template <typename T> struct A { T t; U x; };

    and I want to define U, such that if T is char, then U will be int, if T is float, then U will be double etc. Is this possible via templates, or do I have to declare something like

    struct A_char { char t; int x; };
    struct A_float { float t; double x; };

    and handle things manually?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Is it not possible for you to do

    template <typename T, typename U> struct A { T t; U x; };

    ?

    Comment

    • buchtak
      New Member
      • Mar 2009
      • 4

      #3
      No, it is not, because in my case, compiler deduces the type T from another object, which is determined only by single type T. For instance, I have std::vector<sho rt int> input_array and I want to create struct input_character istics, which will contain input_array sum of squares, average value etc., all of which should have types based on T (but are different). Passing two template arguments would allow me/user to define meaningless definitions like int avg. value for double precision input, which could result in incorrect values.

      Anyways, problem is already solved using type traits.

      template <typename T> struct _A;
      template <> struct _A<int> { typedef __int64 type; };
      template <> struct _A<float> { typedef double type; };

      template <typename T> struct A { typename _A<T>::type x; };

      Comment

      Working...