std::function and std::bind were born inside the Boost C++ Library, but they were incorporated into the new C++11 standard.
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void excute(const vector<function<void ()>>& fs)
{
for(auto&f:fs){
f();
}
}
void plain_old_func(){
cout<<"I'am old plain"<<endl;
}
class functor{
public:
void operator()() {
cout<<"I'am a functor"<<endl;
}
};
int main()
{
vector<function<void()>> x;
x.push_back(plain_old_func);
functor instance;
x.push_back(instance);
x.push_back([](){
cout<<"HI,I am lamda expression"<<endl;
});
excute(x);
return 0;
}
std::function and std::bind were born inside the Boost C++ Library, but they were incorporated into the new C++11 standard.
#include <functional>
#include <iostream>
using namespace std;
using namespace std::placeholders;
int mutiply(int a,int b){
return a*b;
}
int main()
{
auto f=bind(mutiply,5,_1);
for(int i=0;i<10;i++){
cout<<"5*"<<i<<"="<<f(i)<<endl;
}
return 0;
}
output:
50=0
51=5
52=10
53=15
54=20
55=25
56=30
57=35
58=40
59=45
#include <functional>
#include <iostream>
using namespace std;
using namespace std::placeholders;
void show(const string& a,const string&b,const string&c){
cout<<a<<":"<<b<<":"<<c<<";"<<endl;
}
int main()
{
auto x=bind(show,_1,_2,_3);
auto y=bind(show,_2,_3,_1);
auto z=bind(show,"hello",_2,_1);
x("one","two","three");
y("one","two","three");
z("one","two");
return 0;
}
one:two:three;
two:three:one;
hello:two:one;
std::function and std::bind: what are they & when they should be used?
xx