功能指针比较

问题描述

我想编写一个函数,该函数的行为取决于参数是哪个函数。如我所见,我必须比较参数函数指针和其他函数指针。第二个函数在同一个类中声明。

我以为我可以做这样的事情:

void TestClass::testFunction(void inputFunction(functionArgument))
{
  if (*inputFunction== &TestClass::classFunction) {

  }
}

但显然不是。

首先可以这样做吗?如果可以的话,怎么做?

解决方法

您必须传递一个指向函数或成员函数的指针,而不是函数本身。

// Accepts a pointer to function
void TestClass::testFunction(void (*requestedFunction)(int argument))
{
    if (requestedFunction == &TestClass::classFunction)
        ...
}

// Accepts a pointer to member function
void TestClass::testFunction(void (TestClass::*requestedFunction)(int argument))
{
    if (requestedFunction == &TestClass::classFunction)
        ...
}

如果函数指针类型为typedef,则可以简化语法。

typedef void (*function_t)(int argument);

// Accepts a pointer to function
void TestClass::testFunction(function_t requestedFunction)
{
    if (requestedFunction == &TestClass::classFunction)
        ...
}

typedef void (TestClass::*member_function_t)(int argument);

// Accepts a pointer to member function
void TestClass::testFunction(member_function_t requestedFunction)
{
    if (requestedFunction == &TestClass::classFunction)
        ...
}

但是,请注意,如果在多个转换单元中定义函数,则将指向函数的指针进行比较可能会中断,而在多个共享库和/或可执行文件中定义函数时,会发生这种情况。