函数指针
#include <functional>
#include <iostream>
std::function<int(void)> funcPtr;
int foo1(void);
int foo2(void);
int foo3(void);
int foo4(void);
int foo1(void) {
funcPtr = foo2;
std::cout << "foo1: " << std::endl;
return 0;
}
int foo2(void) {
funcPtr = foo3;
std::cout << "foo2: " << std::endl;
return 0;
}
int foo3(void) {
funcPtr = foo4;
std::cout << "foo3: " << std::endl;
return 0;
}
int foo4(void) {
funcPtr = foo1;
std::cout << "foo4: " << std::endl;
return 0;
}
int main() {
funcPtr = foo1;
funcPtr();
funcPtr();
funcPtr();
funcPtr();
return 0;
}
std::bind绑定
#include <functional>
#include <iostream>
std::function<int(void)> funcPtr;
int foo1(void);
int foo2(void);
int foo3(void);
int foo4(void);
int foo1(void) {
funcPtr = std::bind(foo2);
std::cout << "foo1: " << std::endl;
return 0;
}
int foo2(void) {
funcPtr = std::bind(foo3);
std::cout << "foo2: " << std::endl;
return 0;
}
int foo3(void) {
funcPtr = std::bind(foo4);
std::cout << "foo3: " << std::endl;
return 0;
}
int foo4(void) {
funcPtr = std::bind(foo1);
std::cout << "foo4: " << std::endl;
return 0;
}
int main() {
funcPtr = std::bind(foo1);
funcPtr();
funcPtr();
funcPtr();
funcPtr();
return 0;
}
λ表达式
#include <functional>
#include <iostream>
std::function<int(void)> funcPtr;
int foo1(void);
int foo2(void);
int foo3(void);
int foo4(void);
int foo1(void) {
funcPtr = []() { return foo2(); };
std::cout << "foo1: " << std::endl;
return 0;
}
int foo2(void) {
funcPtr = []() { return foo3(); };
std::cout << "foo2: " << std::endl;
return 0;
}
int foo3(void) {
funcPtr = []() { return foo4(); };
std::cout << "foo3: " << std::endl;
return 0;
}
int foo4(void) {
funcPtr = []() { return foo1(); };
std::cout << "foo4: " << std::endl;
return 0;
}
int main() {
funcPtr = []() { return foo1(); };
funcPtr();
funcPtr();
funcPtr();
funcPtr();
return 0;
}
using
#include <iostream>
namespace action
{
enum class RunStatus {
RUNNING,
SUCCESS,
FAILURE
};
class Docking
{
public:
Docking();
~Docking();
void run();
private:
RunStatus enter();
RunStatus findIrda();
RunStatus backDocking();
using FuncPtr = RunStatus (Docking::*)();
FuncPtr funcPtr;
};
Docking::Docking() : funcPtr(&Docking::enter)
{
std::cout << "Docking initialized" << std::endl;
}
Docking::~Docking()
{
}
void Docking::run()
{
(this->*funcPtr)();
}
RunStatus Docking::enter()
{
funcPtr = &Docking::findIrda;
std::cout << "Enter!!!" << std::endl;
return RunStatus::SUCCESS;
}
RunStatus Docking::findIrda()
{
funcPtr = &Docking::backDocking;
std::cout << "Find Irda!!!" << std::endl;
return RunStatus::SUCCESS;
}
RunStatus Docking::backDocking()
{
funcPtr = &Docking::enter;
std::cout << "Back Docking!!!" << std::endl;
return RunStatus::SUCCESS;
}
}
int main()
{
using namespace action;
Docking x;
x.run();
x.run();
x.run();
return 0;
}