示例:
1 #include <vector> 2 #include <string> 3 #include <iostream> 4 #include <functional> 5 6 using namespace std; 7 8 std::function<int (int)> Functional; 9 10 11 int testFunc(int i) { 12 return i; 13 } 14 15 auto lambda = [](int i) -> int { return i; }; 16 17 class Functor { 18 public: 19 int operator()(int i) { 20 return i; 21 } 22 }; 23 24 class test{ 25 public: 26 int foo(int i) { return i; } 27 static int staticFunc(int i) { return i; } 28 }; 29 30 int main() { 31 Functional = testFunc; 32 std::cout << "普通函数:" << Functional(1) << std::endl; 33 34 Functional = lambda; 35 std::cout << "lambda函数:" << Functional(2) << std::endl; 36 37 Functor functor; 38 Functional = functor; 39 std::cout << "仿函数:" << Functional(3) << std::endl; 40 41 test ctest; 42 Functional = test::staticFunc; 43 std::cout << "类静态函数:" << Functional(4) << std::endl; 44 45 Functional = std::bind(&test::foo, ctest, std::placeholders::_1); 46 std::cout << "类成员函数:" << Functional(5) << std::endl; 47 48 std::cin.get(); 49 return 0; 50 }
占个坑先