【问题标题】:Is it possible to equate a function name to another function name?是否可以将一个函数名等同于另一个函数名?
【发布时间】:2013-11-03 14:04:18
【问题描述】:

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

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

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

【问题讨论】:

  • C 还是 C++?你需要的是一个函数指针
  • "我知道以下是不可能的。" - 是的。
  • @H2CO3:酷。我不知道!感谢您告知... :)

标签: c++


【解决方案1】:

这是可能的,假设有两件事:

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

您正在探索的技术与构建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();
  }
}

【讨论】:

  • 强烈赞成将此与跳转表相关联。精彩的解释。
  • @H2CO3:谢谢。 :) 太糟糕了,我被封顶了。
【解决方案2】:

您可以使用函数指针。

有一个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;
}

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

【讨论】:

    【解决方案3】:

    由于这也被标记为 C++,如果您可以访问 C++11,则可以使用 std::function,如果您的编译器支持 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

    【讨论】:

      【解决方案4】:

      既然你选择了 C++

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

      #include <functional>
      #include <iostream>
      
      int function2D( void )
      {
        // ...
      }
      
      int function3D( void ) 
      { 
        // ...
      }
      
      int main()
      {
      
          std::function<int(void)> fun = function2D;
      
          fun();
      
      }
      

      【讨论】:

      • 是的,std::function 可能是在 C++ 中使用的正确方法。
      猜你喜欢
      • 2014-11-06
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      相关资源
      最近更新 更多