C++通过函数指针错误调用成员函数

C++ Calling Member Function by Function Pointer Error

我正在编写离散事件模拟器 (DES),其中事件将是用户编程的函数。 我有一个名为 UserEvents 的 Class 和一个名为 Add

的私有成员函数
    void Add(const void *Parameters, void *ReturnValue);

我正在尝试创建一个向量来存储以下结构:

 typedef struct FunctionPointerAlias { std::string FAlias; void(UserEvents::*FPointer)(const void*, void*); };

基于一个字符串,我想调用不同的函数。因此 switch 会很好,但 switch 不能处理字符串(而且我不想散列我的字符串)。 所以我创建了一个带有结构(字符串别名,函数指针)的向量,然后我将遍历我的向量以查找用户输入的字符串,恢复相应的函数指针并调用它。

所有用户函数都应为 void 类型,接收参数并通过 void* 指针 returning 值:

void UserEvents::Add(const void *Parameters, void *ReturnValue)
{
    int *A = (int*)Parameters;
    int *B = A;
    B++;

    int *C = (int*)ReturnValue;
    *C = *A + *B;

    //memcpy(ReturnValue, &C, sizeof(int));
    return;
}

(TL;DR) 问题出在我尝试调用函数指针指向的函数时。我在 "Add" if.

中 return 正上方的行中收到错误 "Expression preceding parentheses of apparent call must have (pointer-to-) function type"
    void UserEvents::Choose(const std::string Alias, const void *Parameters, void *ReturnValue)
{
    if (Alias == "Example")
    {
        // *ReturnValue = Function(Parameters)
        return;
    }

    if (Alias == "Add") {
        void (UserEvents::*FunctionPointer)(const void*, void*) = &UserEvents::Add;
        (*FunctionPointer)(Parameters, ReturnValue);
        return;
    }
}

我认为通过指针调用该成员函数的语法应该是例如

( this->*FunctionPointer )( Parameters, ReturnValue );

C++ 有两个运算符,.*->*,专门用于通过指针访问 class 成员。这是 article on the topic。无处不在的 * 运算符只是不适用于 class 成员指针。

我不太明白你需要什么,所以我试着做一些通用的,你应该在你自己的模式中使用class:

#include <iostream>
#include <string>

typedef void(*STR_FUNC)(const void*, void*);

struct FUNCTION_POINTER_ALIAS
{
    std::string FAlias;
    STR_FUNC fn;
};

void FN0(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN0" << std::endl;
}

void FN1(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN1" << std::endl;
}

void FN2(const void *Parameters, void *ReturnValue)
{
    std::cout << *(std::string*) Parameters << " FN2" << std::endl;
}

int main()
{
    FUNCTION_POINTER_ALIAS Items[] = {{"str0", FN0}, {"str1", FN1}, {"str2", FN2}};
    for (int i = 0; i < sizeof(Items) / sizeof(FUNCTION_POINTER_ALIAS); ++i)
        Items[i].fn(&Items[i].FAlias, NULL);
}