Getting the type of passed argument in variadic function

二次信任 提交于 2019-12-10 23:23:34

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3564061/getting-the-type-of-passed-argument-in-variadic-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!