1. 程式人生 > 其它 >C++仿函式的基本使用

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;
}