宏中的变量参数 [英] Variable arguments inside a macro

查看:126
本文介绍了宏中的变量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数foo1(a,b)& foo2(a,b,c)和一个宏

I have two functions foo1(a,b) & foo2(a,b,c) and a macro

#define add(a,b) foo(a,b)

我需要重新定义宏才能完成,

I need to re-define macro to accomplish,

1.如果使用2个参数调用add(),则调用foo1

1.if add() is called with 2 parameters, then call foo1

  1. 如果使用3个参数调用add(),则调用foo2

是VA_ARGS选项的新手.我该怎么做

Im new to the option VA_ARGS. How can I do that

推荐答案

如果您必须使用可变参数宏,那么这里有一个窍门.

If you must use variadic macros, then here is a trick.

#define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                            int(*)[2]: add2,       \
                            int(*)[3]: add3) (__VA_ARGS__)

  • 让宏创建一个复合文字数组.此数组的大小取决于参数的数量.
  • 获取复合文字的地址,以获取数组指针类型.
  • _Generic检查您获得的类型,然后基于该类型调用适当的函数.
    • Have the macro create a compound literal array. The size of this array will depend on the number of arguments.
    • Grab the address of the compound literal, to get an array pointer type.
    • Let _Generic check which type you got, then call the proper function based on that.
    • 这是100%标准C语言,而且输入安全.

      This is 100% standard C and also type safe.

      演示:

      #include <stdio.h>
      
      
      #define add(...) _Generic ( &(int[]){__VA_ARGS__}, \
                                  int(*)[2]: add2,       \
                                  int(*)[3]: add3) (__VA_ARGS__)
      
      int add2 (int a, int b);
      int add3 (int a, int b, int c);
      
      int main (void)
      {
        printf("%d\n", add(1, 2));
        printf("%d\n", add(1, 2, 3));
      //printf("%d\n", add(1, 2, 3, 4)); Compiler error for this.
      }
      
      
      int add2 (int a, int b)
      {
        return a + b;
      }
      
      int add3 (int a, int b, int c)
      {
        return a + b + c;
      }
      

      这篇关于宏中的变量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆