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

时间:2013-10-24 17:58:08

标签: c++

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

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

for(....) {
  function();
}

4 个答案:

答案 0 :(得分:5)

有可能,假设有两件事:

  1. function2D()function3D()都具有相同的签名和返回类型。
  2. function是一个函数指针,具有与function2Dfunction3D相同的返回类型和参数。
  3. 您正在探索的技术与构建jump table时使用的技术非常相似。您有一个函数指针,您可以根据运行时条件在运行时分配(和调用)。

    以下是一个例子:

    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();
      }
    }
    

答案 1 :(得分:4)

您可以使用函数指针。

有一个tutorial here,但基本上你所做的就是这样声明:

void (*foo)(int);

其中函数有一个整数参数。

然后你这样称呼它:

void my_int_func(int x)
{
    printf( "%d\n", x );
}


int main()
{
    void (*foo)(int);
    foo = &my_int_func;

    /* call my_int_func (note that you do not need to write (*foo)(2) ) */
    foo( 2 );
    /* but if you want to, you may */
    (*foo)( 2 );

    return 0;
}

因此,只要你的函数具有相同数量和类型的参数,你就应该能够做你想做的事。

答案 2 :(得分:2)

由于这也标记为C ++,如果您有权访问std::function,则可以使用C++11;如果您的编译器支持C ++ 98/03和TR1,则可以使用std::tr1::function

int function2d();
int function3D(); 

int main() {
    std::function<int (void)> f; // replace this with the signature you require.
    if (dimension == 2)
        f = function2D;
    else if (dimension == 3)
        f = function3D;
    int result = f(); // Call the function.
}

如其他答案中所述,请确保您的功能具有相同的签名,一切都会很好。

如果您的编译器未提供std::functionstd::tr1::function,则始终为boost library

答案 3 :(得分:1)

因为你选择了C ++

这是C ++ 11中的std::function示例

#include <functional>
#include <iostream>

int function2D( void )
{
  // ...
}

int function3D( void ) 
{ 
  // ...
}

int main()
{

    std::function<int(void)> fun = function2D;

    fun();

}