#include <iostream>
#include <functional>
using namespace std;
function<int(int)> callback;
int (*func1)(int);
int sum1(int a){
return a;
}
template<typename T>
T sum2(T a){
return a;
}
struct sum3{
int operator()(int x){
return x + 9;
}
};
template<typename T>
struct sum4{
T operator()(T a){
return a - 100;
}
};
template<typename T>
struct sum5{
static T func(T a){
return a + 100;
}
};
struct sum6{
static int func(int a){
return a / 2;
}
};
struct sum7{
int func(int a){
return a * 3;
}
};
template<typename T>
struct sum8{
T func(T a){
return a * 10;
}
};
int main(){
//function pointer
func1 = sum1;
callback = func1;
cout << callback(10) << endl;;
//function
callback = sum1;
cout << callback(10) << endl;;
//template function
callback = sum2<bool>;
cout << callback(5) << endl;
//function object
callback = sum3();
cout << callback(20) << endl;
cout << sum3{}(10) << endl;
//lambda
callback = [](int a){
return a * 2;
};
cout << callback(20) << endl;
//template function object
callback = sum4<int>();
cout << callback(50) << endl;
//template object static function
callback = sum5<int>::func;
cout << callback(30) << endl;
//object static function
callback = sum6::func;
cout << callback(50) << endl;
// std::bind()
// member function
sum7 temp;
callback = bind(&sum7::func, temp, std::placeholders::_1);
cout << callback(26) << endl;
// template member function
sum8<int> func2;
callback = std::bind(&sum8<int>::func, func2, std::placeholders::_1);
cout << callback(20) << endl;
// std::function (move and copy)
// = copy
std::function<int(int)> callback2 = callback;
cout << callback2(20) << endl;
//move
std::function<int(int)>&& callback3 = std::move(callback);
cout << callback3(20) << endl;
cout << callback(20) << endl;
// () copy
std::function<int(int)> callback4(callback);
cout << callback4(20) << endl;
cout << plus<int>()(1, 2) << endl;
return 0;
}
c++11 std::function demo函数
于 2023-03-08 19:33:09 首次发布