获取可变参数函数中传递参数的类型 [英] Getting the type of passed argument in variadic function
本文介绍了获取可变参数函数中传递参数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有什么技巧可以获取传入参数的类型而不显式声明字符串中的类型作为参数之一?
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
如果是A类型
调用函数A
else if 是类型 B
else if is type B
调用函数B.
可变参数模板可以解决这个问题吗?
Could variadic template solve that?
谢谢.
推荐答案
一个可变参数模板肯定能解决这个问题:
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);
}
但这仅在 C++0x 中可用.
But this is only available in C++0x.
如果您指的是 var_args
中的可变参数函数,那么这些参数不带有任何类型信息.
If you mean variadic functions as in var_args
, then those arguments don't carry any type information with them.
这篇关于获取可变参数函数中传递参数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文