views:

82

answers:

4

Is it possible to do something along the lines of:

type t = int;//this would be a function which identifies what type the next argument is
if( t == int )
    printf( "%d", va_arg( theva_list, t ) );

in a relatively trivial way? The only object I know which can hold a type is type_info and I can't work out how to use it in this way.

Thanks, Patrick

+5  A: 

Generally speaking, no. Types can only really be stored, manipulated, etc., at compile time. If you want something at run time, you have to convert (usually via rather hairy metaprogramming) the type to a value of some sort (e.g., an enumeration).

Perhaps it would be better if you gave a somewhat higher level description of what you're really trying to accomplish here -- the combination of variable argument lists with an attempt at "switch on type" sounds like a train crash about to happen...

Jerry Coffin
Don't forget that there's RTTI which allows some type based processing.
Skizz
Thought so. Really don't want to describe it as I am embarrassed I ever came up with the idea, but it would have saved me time had it been possible. Thanks
Patrick
+1  A: 

Not in the way you might think. Types like "int" are evaluated at compile type. You want to evaluate a type at runtime.

Probably you want to make "t" reference a function, or an instance of a class that has a virtual function, one for each type. Essentially you want the command pattern, where the command is "format a value" and the different instances of the command correspond to the different types that can be formatted.

Willis Blackburn
+1  A: 

Use specialization:

  void smart_print(int t)
  {
     printf("%d", i);
  }
  void smart_print(double f)
  {
     printf("%g", f);
  }

But with help of templates you can also resolve pointer to expected function, so treat pointer as identifier of type and you will get desired result

Dewfy
A: 

You should look at how the << and >> operators work for the stream classes (cout and cin for example). Perhaps that will give you an idea about how to solve your problems - i.e. overloaded functions.

Skizz