【问题标题】:Different types of functions as arguments in C++不同类型的函数作为 C++ 中的参数
【发布时间】:2012-07-19 07:31:45
【问题描述】:

我正在编写一个程序,我需要针对不同的情况使用不同的函数,并且我需要广泛使用这些函数。所以,我认为最好的方法是将函数作为参数传递。两者都是双重功能。但是,每个函数所需的参数数量是不同的。我该怎么做?下面我给出一个程序的基本场景。

if (A > B){
func(double x, double y, double func_A(double a1, double a2));
}else{
func(double x, double y, double func_B(double b1, double b2, double b3));
}

【问题讨论】:

    标签: c++ c function arguments


    【解决方案1】:

    你可以重载函数func来接受不同的回调作为参数:

    double func_A(double a1, double a2)
    {
        return 0;
    }
    double func_B(double a1, double a2, double a3)
    {
        return 0;
    }
    
    typedef double (*FUNCA)(double,double);
    typedef double (*FUNCB)(double,double,double);
    
    void func(double x, double y, FUNCA)
    {
    }
    void func(double x, double y, FUNCB)
    {
    }
    
    int main()
    {
        func(0,0,func_A); //calls first overload
        func(0,0,func_B); //calls second overload
    }
    

    【讨论】:

    • 但是我必须分别为 func_A 和 func_B 定义 func,对吗?这对我来说太长了,我正在努力避免这种情况。
    • @PopulationXplosive 那么你不能,因为两者是不同的类型。
    • :(谢谢。其他编程语言有这个功能吗?
    • 在不知道函数采用哪些参数的情况下如何定义函数?
    • @CorporalTouchy 我想他知道他们采用什么参数。
    【解决方案2】:

    C++ 中允许函数重载,所以只需使用它。 Luchian Grigore 给你举了一个例子

    【讨论】:

      【解决方案3】:

      一种简单的方法是让 func 重载调用一个简单的实现函数,该函数接受指向 double(double, double)double(double, double, double) 的单独指针,不适用的将是 NULL...

      void func_impl(double x, double y, double (*f)(double, double), double (*g)(double, double, double))
      {
          ...
          if (...)
               f(a, b);
          else
               g(a, b, c);
          ...
      }
      
      void func(double x, double y, double (*f)(double, double))
      {
          func_impl(x, y, f, NULL);
      }
      
      void func(double x, double y, double (*g)(double, double, double))
      {
          func_impl(x, y, NULL, g);
      }
      
      void caller(...)
      {
          ...
          if (A > B)
              func(x, y, func_A);
          else
              func(x, y, func_B);
      } 
      

      【讨论】:

      • 谢谢。这是个好主意。但是,问题是我将在没有任何条件语句的情况下使用 func_A 和 func_B。就像我在整个 func_impl 中使用了一个函数,比如 func_type。它可能是 func_A 或 func_B,具体取决于条件。所以,问题是我将如何使用单个变量来处理 func_impl 中的 func_A 或 func_B。此外,func_A 和 func_B 的变量将在整个 func_impl 中发生变化。
      猜你喜欢
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 2011-12-18
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多