如何在C++上创建一个接收函数、调用函数并返回函数的函数

How to create a function that receives a function, calls it and returns it on C++?

本文关键字:函数 调用 返回 一个 C++ 创建      更新时间:2023-10-16

我正在尝试创建一个函数,该函数接收一个函数、调用它并将其返回。我已经尝试了几种方法,包括很多模板组合,但似乎都不起作用。正确的方法是什么?

template <typename Functor>
Functor your_function(Functor toCall)
{
    toCall();
    return toCall;
}

如果你想返回函子返回的内容,那么你可以使用这样的东西:

// Requires C++11
#include <type_traits>
template <typename Functor>
typename std::result_of<Functor()>::type your_function(Functor toCall)
{
    return toCall();
}

还要注意的是,这将在带有decltype(auto):的C++14中变得更容易

//Requires C++14    
template <typename Functor>
decltype(auto) your_function(Functor toCall)
{
    return toCall();
}

一个函数不能接收另一个函数作为参数——C不允许,C++也不允许。

但是,您可以将指针作为参数传递给函数,然后通过该指针调用该函数。

#include <iostream>
int f() { std::cout << "called fn"; return 2; }
typedef int (*ptr)();
int g(ptr p) { return p(); }
int main(){
    std::cout << g(f);
}

结果:

called f
2

如果您愿意使用函数模板而不是函数,您可以将函数的名称作为模板参数传递并调用它。在大多数的情况下,最好使用函子(重载operator()的类的实例,以便可以像函数一样调用它)而不是函数。

算法:

  1. 使函数接收作为函数指针的参数
  2. 使用函数指针调用函数
  3. 返回函数指针。函数在C和C++中不是一流的对象。因此,您需要使用指向函数的指针

以下是传递函数指针作为其参数之一的函数的语法:

int Func (int (*funcToCall) (int, int)) /* This is how to receive the function as a parameter */
{
    int val = funcToCall (1, 2); /* This is how to call the function once it's received as a parameter */
    return (val);
}
int FuncToBePassed (int x, int y) /* This is a sample function that fits the format we need to pass into Func */
{
    return (x+y);
}
printf ("%dn", Func (FuncToBePassed)); /* This is how to pass the function reference to the first function */

因此,在本例中,我们有一个带有两个int参数的函数(FuncToBePassed),然后还有一个函数(Func),它希望传递一个类似FuncToBePassed的函数。最后,最后一行代码就是这样做的,调用Func并将对FuncToBePassed的引用传递给它。

顺便说一句,如果你不完全致力于使用C++,我强烈建议你使用C#,因为传递函数等细节设计得更好。所以,如果你打算花时间掌握一门语言,那就选择一门更实用的语言。除非您正在维护一些已经在C++中的代码,这是可以理解的。。。希望我回答了你的问题!