如何在C++上创建一个接收函数、调用函数并返回函数的函数
How to create a function that receives a function, calls it and returns it on C++?
我正在尝试创建一个函数,该函数接收一个函数、调用它并将其返回。我已经尝试了几种方法,包括很多模板组合,但似乎都不起作用。正确的方法是什么?
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()
的类的实例,以便可以像函数一样调用它)而不是函数。
算法:
- 使函数接收作为函数指针的参数
- 使用函数指针调用函数
- 返回函数指针。函数在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++中的代码,这是可以理解的。。。希望我回答了你的问题!
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销