1. Function pointers in C language
First look at an example test_fun.cpp of a function pointer:
#include<iostream>
//定义函数指针
typedef int (*func)();
using namespace std;
int test1(){
cout<<"hello, test1"<<endl;
return 0;
}
int test2(){
cout<<"hello, test2"<<endl;
return 0;
}
int main(int argc, char * argv[]){
func fp = test1;
fp();
fp = test2;
fp();
return 0;
}
The execution results are as follows:
Two, the role of std::function
In fact, the function of std::function is similar to the function pointer above.
But std::function is more powerful than function pointers and has more application scenarios. std::function is a callable object wrapper, and a callable object satisfies one of the following conditions:
(1) Function pointer
(2) Class object with operator() member function (legendary functor), lambda expression
(3) Class object that can be converted into a function pointer
(4) Class member (function) pointer
( 5) bind expressions or other function objects
In actual programming, there are mainly the following scenarios:
(1) Bind a function (ordinary function or static function)
(2) Implement a callback function
(3) As a function input parameter
3. A few examples
1. Bind a function
#include <iostream>
#include <functional>
using namespace std;
int test1(){
cout<<"hello, test1"<<endl;
return 0;
}
int main(int argc, char * argv[]){
std::function<int(void)> fr_test1 = test1;
fr_test1();
return 0;
}
2. As a callback function
#include <iostream>
#include <functional>
using namespace std;
class A{
function<void()> callback;
public:
A(){};
A(const function<void()>& f) : callback(f) {};
void notify(void){
callback();
}
void init(const function<void()>& f){
callback = f;
}
};
class Foo {
public:
// Foo foo;
// foo(); //此时会执行operator()方法
void operator()(void) {
cout << __FUNCTION__ << endl;
}
};
void test(){
cout << "test()" << endl;;
}
int main(void)
{
Foo foo;
A aa(foo);
aa.notify();
A bb;
bb.init(test);
bb.notify();
}
3. As a function input parameter
#include <iostream>
#include <functional>
using namespace std;
void call_when_even(int x, const std::function<void(int)>& f) {
if (!(x & 1)) {
f(x);
}
}
void output(int x) {
cout << x << " ";
}
int main(void){
for (int i = 0; i < 10; ++i) {
call_when_even(i, output);
}
cout<<endl;
return 0;
}
reference:
(1) Explain the functions of C++ in simple terms
(2) std::function and lambda expressions of c++11 new features