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

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

问题描述

我有两个函数 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天全站免登陆