將**普通函數指針**轉換為**函數對象**(可調用對象),使其能用於STL算法要求函數對象的場合。
#include
#include
#include
int u_func(int x) { return x * 2; }
int b_func(int x, int y) { return x + y; }
int main() {
// 一元函數適配
std::pointer_to_unary_function uf = std::ptr_fun(u_func);
std::cout << uf(5) << std::endl; // 10
std::cout << std::ptr_fun(u_func)(5) << std::endl; // 直接用
// 二元函數適配
std::pointer_to_binary_function bf = std::ptr_fun(b_func);
std::cout << bf(3, 4) << std::endl; // 7
std::cout << std::ptr_fun(b_func)(3, 4) << std::endl; // 直接用
// 實際應用:配合STL算法
int arr[] = {1,2,3,4,5};
std::transform(arr, arr+5, arr, std::ptr_fun(u_func)); // 每元素*2
// arr 變為 {2,4,6,8,10}
}
C++11起推薦使用 **lambda表達式** 或 **`std::function`** / **`std::bind`**:
// Lambda(更直觀、無額外開銷)
std::transform(arr, arr+5, arr, [](int x){ return x*2; });
// std::function
std::function f = u_func;
std::transform(arr, arr+5, arr, f);