用户提供的函数内部代码

时间:2012-06-19 20:16:13

标签: c++ c

假设我已经为windows和mac定义了相同的函数,具有不同的返回值,如下所示:

#ifdef _WIN32

// Windows code
int porting(int input){
  return input + 360;
}

#endif

#ifdef __APPLE__

// Mac code
int porting(int input){
  return input + 180;
}

#endif

有没有办法允许用户指定在porting()内运行的代码,而不是有多个定义?

1 个答案:

答案 0 :(得分:1)

C ++作为一种编译语言,没有eval()函数,许多解释语言(如PHP或Javascript)都有。{3}}函数。无法在运行时执行 textual 用户提供的代码。

或许回调足以满足您的需求?

示例:

typedef int (*userfunction)(int);

userfunction thefunction;

void set_user_function(userfunction uf)
{
    thefunction = uf;
}

int porting(int input)
{
    return thefunction(input);
}
相关问题