简体   繁体   English

在C中将类型作为参数赋予va_arg

[英]Give type as argument like va_arg in C

va_arg(a,type) macro expands to __builtin_va_arg(a,type) which is built-in part of compiler. va_arg(a,type)宏扩展为__builtin_va_arg(a,type) ,它是编译器的内置部分。

Is it possible to implement type based functionality, if yes how? 是否可以实现基于类型的功能,如果是,如何?

Notice that va_arg cannot determine the actual type of the argument passed to the function, but uses whatever type is passed as the type macro argument as its type. 请注意, va_arg无法确定传递给函数的参数的实际类型,但使用作为类型宏参数传递的任何类型作为其类型。

Lets see how va_arg works, one possibility from here , is 让我们看看va_arg是如何工作的, 这里有一种可能性

#define va_arg(ap,t) (*(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)))

First of all, it's a MACRO not a function. 首先,它是一个MACRO而不是一个功能。

If you want write a type base MACRO as same as var_arg , you have two main tools, pointers and sizeof . 如果你想写一个类型基MACRO和var_arg ,你有两个主要的工具, pointerssizeof

You can increase/decrease/lookup a pointer with sizeof steps. 您可以使用sizeof步骤增加/减少/查找指针。

With the preprocessor, you can indeed implement type based functionality, although it is limited. 使用预处理器,您确实可以实现基于类型的功能,尽管它是有限的。 Don't forget that #define directives act with copy/paste, so you can not compare types in C standard, for instance(*). 不要忘记#define指令与复制/粘贴一起使用,因此您无法比较C标准中的类型,例如(*)。

However, you can reuse a type argument to build type-generic functions. 但是,您可以重用type参数来构建类型泛型函数。 Here is an example of a min generic function: 以下是min通用函数的示例:

#define DEFINE_MIN(type)        \
int min_##type(type a, type b)  \
{ return a < b ? a : b; }       

By the way, a gcc extension, typeof , gives the type of an expression (it doesn't rely on the programmer arguments anymore). 顺便说一下, gcc扩展名typeof给出了表达式的类型(它不再依赖于程序员参数)。 Moreover, more recently, the C11 _Generic keyword permits you to write different treatment for expressions of different types. 此外,最近,C11 _Generic关键字允许您为不同类型的表达式编写不同的处理方式。

(*) In the case of va_arg , the type argument is often use to get the size of type and type* . (*)对于va_argtype参数通常用于获取typetype*的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM