C++函数传递函数指针、仿函数、绑定器、可调用对象

只定义void testFunc(int num, const std::function<int(int)>& functor)就可以,其他的相当于这个函数的特化版本

#include <iostream>
#include <functional>
using namespace std;

int func1(int num)
{
    cout << " func1: " << num << endl;
    return 1;
}

// 仿函数
class funcClass
{
public:
    int operator()(int num) const{
        cout << " funcClass: " << num << endl;
        return 1;
    }
};

// 可调用对象
std::function<int(int)> func3 = [](int num)->int{
        cout << " function:fun3 "<< num << endl;
        return 1;
    };

// 可以接受原生函数指针、类的静态成员函数、仿函数、绑定器bind、可调用对象function
void testFunc(int num, const std::function<int(int)>& functor)
{
    cout << "调用绑定器函数" << endl;
    functor(num);
}

// 相当于进行了特化
void testFunc(int num, int (*functor)(int))
{
    cout << "调用函数指针" << endl;

    functor(num);
}

// 相当于进行了特化
void testFunc(int num, const funcClass& functor)
{
    cout << "调用仿函数" << endl;

    functor(num);
}



// g++
int main()
{
    funcClass()(1); // 创建临时对象调用函数
    testFunc(2, func1);    // 传递函数指针

    // error:匿名函数,函数指针与可调用对象的重载冲突
    // testFunc(3, [](int num)->int{
    //     cout << "lambda: " << num << endl;
    //     return 1;
    // });
    
    testFunc(4, funcClass());   // 传递仿函数
    testFunc(5, func3);         // 传递可调用对象
    testFunc(6, std::bind(funcClass(), placeholders::_1));         // 传递绑定器
}

posted @ 2023-08-01 15:26  小小灰迪  阅读(28)  评论(0编辑  收藏  举报