Topic: Can we check the actual data type in templ


Author: tholaday@jpmorgan.com (Thomas Holaday,COMM)
Date: 23 Nov 1994 15:52:00 GMT
Raw View
In article 94Nov18162021@orange.ridgefield.sdr.slb.com, saito@orange.ridgefield.sdr.slb.com (Naoki Saito) writes:
>Hello!  I would like to know whether it is possible to check the data type
>in the template constructs.  What I want to do can be described roughly
>as follows:
>
>template <class DT>
>void f(DT x)
>{
> switch (datatype of(DT)) // check what the actual DT is in the calling prog.
>  {
>   case "int":
>     task_int(x);
>     break;
>   case "float":
>     task_float(x);
>     break;
>   case "double":
>     task_double(x);
>     break;
> }
>}

Note that renaming task_int, task_float, task_double to "task" and using ordinary function overloading reduces this example to a one liner:

        template <class DT> void f(DT x) { task(x); return; }

Let's assume you can't rename these functions, though.  Well, write your own:

 inline task(int i) { task_int(i) ; return; }
 inline task(float f) { task_float(f) ; return; }
 inline task(double d) { task_double(d) ; return; }


If you want to "switch" on something other than type, such as SinglyLinkedness
vs DoublyLinkedness, use the Stepanov technique described in Stroustrup's _Design_and_Evolution_of_C++_ chapter on templates.  Take a completely
arbitrary example (to show how powerful this technique can be), where you want
to do one thing for your classes (A, B, C) and a different thing for my classes
(X, Y, Z):

class Saitoness {}; class Holadayness{} ;

inline Saitoness author(A) { return Saitoness(); }
inline Saitoness author(B) { return Saitoness(); }
inline Saitoness author(C) { return Saitoness(); }
inline Holadayness author(X) { return Holadayness(); }
inline Holadayness author(Y) { return Holadayness(); }
inline Holadayness author(Z) { return Holadayness(); }

template <class T>
inline void doIt_(T t, Saitoness) { do_Saito(t) ; }

template <class T>
inline void doIt_(T t, Holadayness) { do_Holaday(t) ; }

template <class T>
void doIt(T t)
{
    doIt_(t,author(t));
}

This collection of code has the same effect as

 template <class T>
 void doIt(T t)
 {
 switch (T)
 case A:
 case B:
 case C:
     do_Saito(t);
     break;
 case X:
 case Y:
 case Z"
     do_Holaday(t);
     break;
 };

You'll see this technique used heavily in the Standard Template Library.