函数指针就是指向函数地址的指针
int Sum(int a, int b) {
return a + b;
}
typedef int(*SumFunc)(int x, int y);
// --------
SumFunc sum = Sum;
std::cout << sum(1, 2) << std::endl;
重载了 operator() 的类对象:
class SumClass {
public:
SumClass(int padding): padding(padding){}
int operator()(int a, int b) {
return a + b + padding;
}
private:
int padding;
};
// ---------------------
SumClass sumObj(3);
std::cout << sumObj(1, 2) << std::endl;
lambda 表达式内部会创建一个上面所说的函数对象, 不过是匿名的, 只有编译器知道类名是什么. lambda 可以捕获外部的变量, 都会转换为匿名函数对象的属性值来保存.
int padding = 3;
auto sum_lambda = [padding](int a, int b) -> int {
return a + b + padding;
};
std::cout << sum_lambda(1, 2) << std::endl;
std::function
C++ 对 std::function
的描述:
Class template
std::function
is a general-purpose polymorphic function wrapperInstances of
std::function
can store, copy, and invoke any CopyConstructible Callable target–functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members
std::function
是一个函数包装器模板,一个 std::function
类型对象可以包装以下类型:
std::bind
传递)operator()
操作符的类对象)既然能包装这些类型, 也相当于可以从这些类型转换过来:
class TestClass {
public:
int Sum(int x, int y) {
return x + y;
}
};
// ---------------------
// 包装函数指针
std::function<int(int, int)> sum_func_1 = sum;
std::cout << sum_func_1(1, 2) << std::endl;;
// 包装函数对象
std::function<int(int, int)> sum_func_2 = sumObj;
std::cout << sum_func_2(1, 2) << std::endl;;
// 包装 Lambda (即便 capture 了参数)
std::function<int(int, int)> sum_func_3 = sum_lambda;
std::cout << sum_func_3(1, 2) << std::endl;;
// 包装类成员函数指针
TestClass test_obj;
using std::placeholders::_1;
using std::placeholders::_2;
std::function<int(int, int)> sum_func_4 = std::bind(&TestClass::Sum, &test_obj, _1, _2);
std::cout << sum_func_4(1, 2) << std::endl;;
std::function
// lambda without capturing any value -> function ptr
SumFunc func_ptr = [/*padding (error) */](int x, int y) -> int {
return x + y;
};
std::cout << func_ptr(1, 2) << std::endl;;
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有