Loading

C++仿函数的基本使用

C++ 提供了仿函数

概念:
  重载函数调用操作符的类,其对象成为函数对象
  函数对象使用重载()时,行为类似函数调用,也叫仿函数
本质:
仿函数是一个类,不是一个函数
特点:
  仿函数在使用时可以像普通函数一样调用
  函数对象不是普通函数,它可以拥有自己的状态,比如统计调用了多少次
  仿函数可以作为形参参数传递(类似函数编程)
分类:
  算术仿函数
  关系仿函数
  逻辑仿函数

基本使用

#include <vector>
#include <string>
#include <iostream>
#include <functional>

using namespace std;

std::function<int (int)> Functional;


int testFunc(int i) {
    return i;
}

auto lambda = [](int i) -> int { return i; };

class Functor {
public:
    int operator()(int i) {
        return i;
    }
};

class test{
public:
    int foo(int i) { return i; }
    static int staticFunc(int i) { return i; }
};

int  main() {
    Functional = testFunc;
    std::cout << "普通函数:" << Functional(1) << std::endl;

    Functional = lambda;
    std::cout << "lambda函数:" << Functional(2) << std::endl;

    Functor functor;
    Functional = functor;
    std::cout << "仿函数:" << Functional(3) << std::endl;

    test ctest;
    Functional = test::staticFunc;
    std::cout << "类静态函数:" << Functional(4) << std::endl;

    Functional = std::bind(&test::foo, ctest, std::placeholders::_1);
    std::cout << "类成员函数:" << Functional(5) << std::endl;

    std::cin.get();
    return 0;
}

也可以使用函数对象、lambda函数、struct实现函数式编程,嵌套函数定义

#include<iostream>
using namespace std;
void foo()
{
    // void innerfoo()
    // {
        // cout << "innerfoo()" << endl;
    class Inner
    {
    public:
        void operator()(){
            cout << "inner object()" << endl;
        }
    };

    Inner inn;
    inn();

    auto lambdafunc = [=]()->int
    {
        cout << "lambdafunc" << endl;
        return 0;
    };

    cout << lambdafunc() <<endl;


    struct func_ 
    {
        void operator () (int n) 
        {
            std::cout << "func " << n << std::endl;
        }       
    } func;
    func(1);
}
int main(int argc, char const *argv[])
{
    foo();
    return 0;
}

运行结果:

posted @ 2022-05-09 18:26  这个世界太乱  阅读(221)  评论(0)    收藏  举报