【问题标题】:How do you pass a function as a parameter? [duplicate]如何将函数作为参数传递? [复制]
【发布时间】:2012-04-25 19:39:12
【问题描述】:

可能重复:
How do function pointers work?

如何将函数作为参数传递?

您还可以将另一个类的函数作为参数传递(使用对象吗?)?

【问题讨论】:

  • 与传递其他任何参数的方式相同。你把它的名字放在你想要传递给它的函数的名字后面的括号内。你在哪个部分有问题?嗯——也许标题并没有说明一切?

标签: c++ function parameters


【解决方案1】:

除了函数指针,您还可以使用 std::function and std::bind(如果您没有 C++11,则可以使用 boost 等价物)。它们提供了多态函数包装器,所以你可以做一些事情,比如定义这个函数,它接受一个std::function,它接受两个整数并返回一个双精度:

double foo(std::function<double(int, int)> f) {
  return 100*f(5,89);
}

然后您可以传递任何与该签名匹配的内容,例如:

struct Adder {
  double bar(double a, double b) { return a+b;}
};

int main() {
  using namespace std::placeholders;
  Adder addObj;
  auto fun = std::bind(&AdderC::bar, &addObj, _1, _2); // auto is std::function<double(int,int)>

  std::cout << foo(fun) << "\n"; // gets 100*addObj.bar(5,89)
}

这些都是易于使用的强大功能,不要被无用的示例误导。您可以包装普通函数、静态函数、成员函数、静态成员函数、仿函数...

【讨论】:

    【解决方案2】:

    有两种方法。

    一个是@dusktreader概述的函数指针。

    另一种是使用functors或函数对象,在其中定义一个类,用函数的参数重载operator(),然后传递该类的一个实例。

    我一直觉得后者更直观,但两者都可以。

    【讨论】:

    • 函子仅在传递给模板函数时才起作用。
    • @MarkRansom 函数对象也可以通过virtual 使用公共基础和动态调度。
    • @MarkRansom 不是std::functions
    【解决方案3】:

    你需要传递一个函数指针。语法并不难,有一个精彩的页面 here 提供了如何在 c 和 c++ 中使用函数指针的详细说明。

    从该页面 (http://www.newty.de/fpt/fpt.html):

    //------------------------------------------------------------------------------------
    // 2.6 How to Pass a Function Pointer
    
    // <pt2Func> is a pointer to a function which returns an int and takes a float and two char
    void PassPtr(int (*pt2Func)(float, char, char))
    {
       int result = (*pt2Func)(12, 'a', 'b');     // call using function pointer
       cout << result << endl;
    }
    
    // execute example code - 'DoIt' is a suitable function like defined above in 2.1-4
    void Pass_A_Function_Pointer()
    {
       cout << endl << "Executing 'Pass_A_Function_Pointer'" << endl;
       PassPtr(&DoIt);
    }
    

    【讨论】:

    • 谢谢,我回家试试这个
    猜你喜欢
    • 2015-11-08
    • 2015-09-28
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-21
    • 2020-08-03
    相关资源
    最近更新 更多