如何使用宏作为函数指针?

How to use macro as function pointer?

如何将宏用作函数指针?我不知道要解决这个问题。我创建了一个草图(不起作用,充满了语法错误)来展示我试图完成的事情。请帮忙!

#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation
#define D1_OUT(x) (x*1024) //I want to use this for Pin1 calculation

struct Pin {
  CalcMethod *calcMethod; //int methodName(int x) { return MACRO(x); }

  Pin(CalcMethod *calcMethodParam) {
    calcMethod = calcMethodParam;
  }

  int calc(int x) {
    return calcMethod(x);
  }
};

#define PIN_COUNT 2
Pin *pins[PIN_COUNT];

void start() {
    pins[0] = new Pin(D0_OUT); //use the D0_OUT macro to calculate
    pins[1] = new Pin(D1_OUT); //use the D1_OUT macro to calculate
    int pin0CalcResult=pins[0]->calc(5); // =5/1024*100
    int pin1CalcResult=pins[1]->calc(6); // =6*1024
}

宏由预处理器处理。它们不存在于编译代码中,因此没有指针。

在现代代码中您应该遵循一条规则,这条规则就是 "don't use macros for furnctions"。函数的宏是一个遗留物,仍然有一些很好的用途,但它们非常罕见。

只需声明一个普通函数

int do_out(int x) {
    return x / 1024 * 100;
}

另见"static const" vs "#define" vs "enum"

您可以,但不建议,使用宏作为命名的 lambda。于是

#define D0_OUT [](int x) { return x / 1024 * 100; }
#define D1_OUT [](auto x) { return x * 1024; }

它应该可以工作。

D0_OUT 示例可用于 C++11,D1_OUT 可用于 C++14。

我知道这是一个旧线程..

假设您不能只将宏更改为函数。也许它是某处库驱动程序的一部分,出于某种原因(例如单元测试)您需要将其传递给另一个函数。您可以将宏包装在您要使用它的 .c 文件中。

所以这个:

#define D0_OUT(x) (x/1024*100) //I want to use this for Pin0 calculation

变成:

static int D0_OUT_wrapper(int x)
{
    return D0_OUT(x);
}

所以包装器像往常一样进入:

pins[0] = new Pin(D0_OUT_wrapper);

如果您可以完全控制正在编写的代码,那么就不要使用宏。