Callable Function
0. Overview
It could happens sometimes that we need to pass a function as parameter to another function. However, it is weird to pass a function directly. Thus, this time we will cover the following method to pass the function as parameter:
- Function Pointer
- Function Object----Functor
- Lambda Expression
- Callable Argument
1. Function Pointer
First of all, when we want to set function A as a parameter of function B, how should we define?
/*
Function name without argument(s) is the address of the function
*/
int Max(int a, int b, bool (*F)(int i, int j)){
// F is a pointer to a function which returns bool and takes 2 int arguments
return F(a,b) ? a : b;
}
test.cpp
// Function pointer
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
bool f1(int a, int b) {
return a < b; }
bool f2(int a, int b) {
return a > b; }
bool f3(int a, int b) {
return a %2 < b %2;}
/*
Function name without argument(s) is the address of the function
*/
int Max(int a, int b, bool (*F)(int i, int j)){
// F is a pointer to a function which returns bool and takes 2 int arguments
return F(a,b) ? a : b;
}
int main (){
list<int> L10 {
5,3,1,2,6};
L10.sort(f3);
for (auto i : L10)
{
cout << i << " ";
}
cout << endl;
cout << Max(2, 5, f3) << endl;
// P is a function pointer
bool (*p)(int m, int n);
// &f1, *f1, **f1, ***f1 all work
p = f1;
cout << f1(2, 8) << " " << p(2,8) << endl;
cout << max(2, 5, [](int m, int n){
return m < n; }) << endl;
list<int> L11 {
4,2,11,5,8};
L11.sort([](int m, int n){
return m %5 < n%5;} );
for (auto i : L11)
{
cout << i << " ";
}
cout << endl;
return 0;
}
2. Lambda Function
A lambda (or lambda expression) consists of three parts: [capture clause](argument list){function body}
#include <iostream>
#include <algorithm>
#include <math.h>
#include <list>
using namespace std;
int main(