storing a type's type for processing variable argument lists
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 trivi开发者_如何学JAVAal 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
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...
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.
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
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.
精彩评论