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

时间:2017-12-24 09:55:01

标签: c++ macros function-pointers

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

#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
}

3 个答案:

答案 0 :(得分:3)

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

现代代码中应该遵循一条规则,该规则是“不要使用宏来制作家具”。功能宏是一种仍然具有一些好用途的残骸,但它们非常罕见。

只需声明一个正常的功能

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

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

答案 1 :(得分:0)

您可以,但不可取,使用名为lambdas的宏。因此

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

它应该有用。

可在C ++ 11中使用的D0_OUT示例和可与C ++ 14一起使用的D1_OUT。

答案 2 :(得分:0)

我知道这是一个旧线程。

假定您不能仅将宏更改为函数。也许它是某个地方的库驱动程序的一部分,由于某些原因(例如单元测试),您需要将其传递给另一个函数。您可以将宏包装在要使用的.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);

如果您完全控制要编写的代码,则不要使用宏。