如何避免在多态打印宏中使用#if [英] how can I avoid the use of #if in a polymorphic print macro

查看:97
本文介绍了如何避免在多态打印宏中使用#if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们尝试运行以下代码:

Let's try to run the following code:

#include <stdio.h>
#define MY_MACRO1(isArray,y) do { \
                      if(isArray) \
                        printf("%d", y[0]); \
                      else \
                        printf("%d", y); \
                     }while(0)

int main()
{
    int a = 38;
    int b[]={42};

    MY_MACRO1(0,a);

    return 0;
}

它返回错误:

main.c: In function ‘main’:
main.c:12:39: error: subscripted value is neither array nor pointer nor vector
                         printf("%d", y[0]); \

好的,因此仅当变量是数组时,我们才需要#if语句来运行y [0]:

Ok, so we would need a #if statement to run y[0] only if the variable is an array:

#define MY_MACRO2(isArray,y) do { \
                      #if isArray \
                      printf("%d", y[0]); \
                      #else \
                      printf("%d", y); \
                      #endif \
                     }while(0)

int main()
{
    int a = 38;
    int b[]={42};

    MY_MACRO2(0,a);

    return 0;
}

但是它返回:

main.c:11:28: error: '#' is not followed by a macro parameter
 #define MY_MACRO2(isArray,y) do { \

总有没有在宏中调用#if语句? 如果没有,我该怎么做?

Is there anyway to call a #if statement inside a macro? if not, how can I do such a thing?

注意:我使用的是IAR 8.20.2

note: I'm using IAR 8.20.2

(此链接没有帮助)

我想知道为什么我不想使用2个不同的宏是因为我需要这样的东西(伪代码):

I you want to know why I would not like to use 2 different macros is because I need to to something like this (pseudo-code):

myFunction(int or array):
   doSomethingWhereIntAndArrayBehavesDifferentlyLikePrintf();
   doSomethingelse();
   doSomethingelse();
   doSomethingWhereIntAndArrayBehavesDifferentlyLikePrintf();
   doSomethingelse();

  • 这非常方便:您可以分解代码.
  • 这是一种实现多态的方法.
  • 它模仿C ++模板功能.
  • 推荐答案

    反正在宏内调用#if语句吗?

    Is there anyway to call a #if statement inside a macro?

    不可能.

    如果没有,我该怎么做?

    if not, how can I do such a thing?

    您可以使用C11 _Generic:

    You could use C11 _Generic:

    #include <stdio.h>
    
    void int_func (int obj)
    {
      printf("%d\n", obj);
    }
    
    void int_arr_func (const int* obj)
    {
      printf("%d\n", obj[0]);
    }
    
    void float_func (float obj)
    {
      printf("%f\n", obj);
    }
    
    #define MY_MACRO2(y) _Generic((y), \
      int:   int_func,                 \
      int*:  int_arr_func,             \
      float: float_func ) (y)
    
    
    int main (void)
    {
        int a = 38;
        int b[]={42};
        float pi = 3.14f;
    
        MY_MACRO2(a);
        MY_MACRO2(b);
        MY_MACRO2(pi);
        return 0;
    }
    

    这篇关于如何避免在多态打印宏中使用#if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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