views:

68

answers:

2

Is there any trick to get the type of the passed in arguments without explicitly stating the type in a string as one of the argument?

To add on the post just now, basically what I want to do is

if is type A

call functionA

else if is type B

call functionB.

Could variadic template solve that?

Thanks.

+3  A: 

No, if they may vary in type, you need to pass some kind of structure specifying what those types are.

Also note that only certain types are allowed, and you're best off restricting it to just pointers.

Variadic templates solve this problem. You'll need a newer compiler, though, and templates need to live in header files. A separate function gets generated for every unique sequence of argument types.

Potatoswatter
A: 

A variadic template surely solves this:

#include <cstdio>

void function_a(int a) { printf("int %d\n", a); }
void function_b(double b) { printf("double %f\n", b); }

void select(int n) { function_a(n); }
void select(double d) { function_b(d); }

template <class T>
void variadic(T a)
{
    select(a);
}

template <class T, class ...Args>
void variadic(T a, Args... args)
{
    select(a);
    variadic(args...);
}

int main()
{
    variadic(1, 3, 2.1, 5.6, 0);
}

But this is only available in C++0x.

If you mean variadic functions as in var_args, then those arguments don't carry any type information with them.

UncleBens