C语言 将变量类型作为函数参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6658593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing variable type as function parameter
提问by freonix
Is it possible to pass variable type as part of a function parameter, e.g.:
是否可以将变量类型作为函数参数的一部分传递,例如:
void foo(varType type)
{
// Cast to global static
unsigned char bar;
bar = ((type *)(&static_array))->member;
}
I remember it has something to do with GCC's typeofand using macros?
我记得它与 GCCtypeof和使用宏有关?
采纳答案by David X
You can't do that for a function, because then it needs to know the types of the arguments (and any other symbols the function uses) to generate working machine code. You could try a macro like:
你不能对一个函数这样做,因为它需要知道参数的类型(以及函数使用的任何其他符号)来生成工作机器代码。您可以尝试使用以下宏:
#define foo(type_t) ({ \
unsigned char bar; \
bar = ((type_t*)(&static_array))->member; \
... \
})
回答by hugomg
You could make an enum for all different types possible, and use a switch to make the dereferencing:
您可以为所有不同的类型创建一个枚举,并使用开关来取消引用:
typedef enum {
CHAR,
INT,
FLOAT,
DOUBLE
} TYPE;
void foo(TYPE t, void* x){
switch(t){
case CHAR:
(char*)x;
break;
case INT:
(int*)x;
break;
...
}
}
回答by FloatingRock
Eh, of course you can. Just use a macro like so:
嗯,当然可以。只需使用这样的宏:
#include <stdio.h>
#define swap(type, foo, bar) ({type tmp; tmp=foo; foo=bar; bar=tmp;})
int main() {
int a=3, b=0;
printf("a=%d, b=%d \n", a, b); // a=3, b=0
swap(int, a, b); // <-- WOOT, check it out!
printf("a=%d, b=%d \n", a, b); // a=0, b=3
return 0;
}
回答by David Gelhar
I don't see how you could do this in the general case, given that C is a statically typed language.
鉴于 C 是一种静态类型语言,我不知道在一般情况下如何做到这一点。
The compiler needs to know at compile time what the type of type *is in order to be able to generate the reference to ->member.
编译器需要在编译时知道是什么类型,type *以便能够生成对->member.

