是否可以将函数名称等同于另一个函数名称?

Sat*_*evi 0 c++

我不确定以下是否可行.有人可以给出这个要求的等价物吗?

if(dimension==2)
  function = function2D();
else if(dimension==3)
  function = function3D();

for(....) {
  function();
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ing 5

假设有两件事情是可能的:

  1. 双方function2D()function3D()具有相同的签名和返回类型.
  2. function是一个函数指针,具有相同的返回类型和参数都function2Dfunction3D.

您正在探索的技术与构建跳转表时使用的技术非常相似.您有一个函数指针,您可以根据运行时条件在运行时分配(和调用).

这是一个例子:

int function2D()
{
  // ...
}

int function3D()
{ 
  // ...
}

int main()
{
  int (*function)();  // Declaration of a pointer named 'function', which is a function pointer.  The pointer points to a function returning an 'int' and takes no parameters.

  // ...
  if(dimension==2)
    function = function2D;  // note no parens here.  We want the address of the function -- not to call the function
  else if(dimension==3)
    function = function3D;

  for (...)
  {
    function();
  }
}
Run Code Online (Sandbox Code Playgroud)