C++ 函數對象(也稱為仿函數或functor)是一種具有成員函數調用操作符(operator())的對象。它們可以像函數一樣被調用,并且可以攜帶狀態(即成員變量)。C++ 函數對象支持以下操作:
class MyFunctor {
public:
    MyFunctor(int x) : value(x) {}
    ~MyFunctor() {}
private:
    int value;
};
operator() 以便像函數一樣被調用。class MyFunctor {
public:
    int operator()(int y) const {
        return value * y;
    }
private:
    int value;
};
const 成員函數調用操作符。class MyFunctor {
public:
    int operator()(int y) const {
        return value * y;
    }
private:
    int value;
};
+、-、* 等,以實現更高級別的抽象和操作。class MyFunctor {
public:
    int value;
    MyFunctor operator+(const MyFunctor& other) const {
        return MyFunctor(value + other.value);
    }
};
std::function 模板類,它可以存儲任何可調用目標(包括函數、函數指針、成員函數指針、Lambda 表達式等)。這使得函數對象可以與標準庫中的算法和其他組件一起使用。#include <iostream>
#include <functional>
int main() {
    MyFunctor f(5);
    std::function<int(int)> func = f;
    std::cout << func(3) << std::endl; // 輸出 15
    return 0;
}
總之,C++ 函數對象提供了豐富的操作,使得它們在實現回調函數、算法和其他需要可調用對象的場景中非常有用。