传送门 ==>> AutoSAR实战系列300讲「糖果Autosar」总目录
函数是一组接受输入、执行某些特定计算并产生输出的语句。使用函数的想法是一起执行一些常见或重复完成的任务,以便为不同的输入一次又一次地编写相同的代码。函数的一般形式是:
return_type function_name([ arg1_type arg1_name, ... ]) {
// 执行操作
}
将函数作为参数传递是C/C++中的一个有用概念。在将自定义比较器函数作为参数传递到std::sort()以根据需要对对象 序列进行排序时,已经使用了这个概念。在本文中,我们将讨论设计接受另一个函数作为参数的函数的不同方法。
一个函数也可以通过将其地址传递给另一个函数来传递给另一个函数。下面是C++ 程序:
C++
// C++ program to pass function as a
// pointer to any function
#include
using namespace std;
// Function that add two numbers
int add(int x, int y)
{
return x + y;
}
// Function that multiplies two
// numbers
int multiply(int x, int y)
{
return x * y;
}
// Function that takes a pointer
// to a function
int invoke(int x, int y,
int (*func)(int, int))
{
return func(x, y);
}
// Driver Code
int main()
{
// Pass pointers to add & multiply
// function as required
cout << "Addition of 20 and 10 is ";
cout << invoke(20, 10, &add)
<< '\n';
cout << "Multiplication of 20"
<< " and 10 is ";
cout << invoke(20, 10, &multiply)
<< '\n';
return 0;
}
输出:
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
在C++ 11中,有一个 std::function<>模板类允许将函数作为对象传递。std::function<>的对象 可以如下创建。
std::function<return_type(arg1_type, arg2-type…)> obj_name
// This object can be use to call the function as below
return_type catch_variable = obj_name(arg1, arg2);
下面是说明将函数对象作为参数传递给另一个函数的程序:
C++
// C++ program to illustrate the passing
// of functions as an object parameter
#include
#include
using namespace std;
// Define add and multiply to
// return respective values
int add(int x, int y)
{
return x + y;
}
int multiply(int x, int y)
{
return x * y;
}
// Function that accepts an object of
// type std::function<> as a parameter
// as well
int invoke(int x, int y,
function<int(int, int)> func)
{
return func(x, y);
}
// Driver code
int main()
{
// Pass the required function as
// parameter using its name
cout << "Addition of 20 and 10 is ";
cout << invoke(20, 10, &add)
<< '\n';
cout << "Multiplication of 20"
<< " and 10 is ";
cout << invoke(20, 10, &multiply)
<< '\n';
return 0;
}
输出:
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
C++ 中的Lambda提供了一种定义内联、一次性、匿名函数对象的方法。这些 lambda 可以在需要将函数作为参数传递的地方定义。下面是说明相同内容的 C++ 程序:
C++
// C++ program to pass the function as
// parameter as a lambda expression
#include
#include
using namespace std;
// Function that takes a pointer
// to a function
int invoke(int x, int y,
function<int(int, int)> func)
{
return func(x, y);
}
// Driver Code
int main()
{
// Define lambdas for addition and
// multiplication operation where
// we want to pass another function
// as a parameter
// Perform Addition
cout << "Addition of 20 and 10 is ";
int k = invoke(20, 10,
[](int x,
int y) -> int {
return x + y;
});
cout << k << '\n';
// Perform Multiplication
cout << "Multiplication of 20"
<< " and 10 is ";
int l = invoke(20, 10,
[](int x,
int y) -> int {
return x * y;
});
cout << l << '\n';
return 0;
}
输出:
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200