6. OOP: Callable Function

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:

  1. Function Pointer
  2. Function Object----Functor
  3. Lambda Expression
  4. 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(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值