std::function
std::function
在<functional>
头文件中定义的,创建的类型可以指向任何可以被调用的:
- 函数指针
- 函数对象
- lambda表达式
std::function
is called a polymorphic function wrapper. 可以用作函数指针或是作为函数的参数实现回调。
std::function
的模板语法如下:
std::function<R(ArgTypes...)>
R
是函数的返回类型ArgTypes
是,
号分隔的函数参数类型
void func(int num, const string& str) {
cout << "func(" << num << ", " << str << ") " << endl;
}
int main() {
std::function<void(int, const string&)> f1 = func;
f1(1, "test);
return 0;
}
lambda expression
// does not accept any parameters
auto basicLambda = [](){ cout << "Hello from Lambda" << endl; };
basicLambda();
// // does not accept any parameters, omit empty parentheses
auto basicLambda = []{ cout << "Hello from Lambda" << endl; };
// accept one parameter
auto parameterspLambda = [](int value){ cout << "This value is" << value << endl; };
parameterspLambda(15);
// return value
auto returningLambda = [](int a, int b) -> int { return a + b; }
int sum = returningLambda(1, 2);
// the return type can be omitted,
// the compiler deduces the return type
auto returningLambda = [](int a, int b){ return a + b; }
Capture variables from its enclosing scope
int data = 123; // the captured value is non-const
auto capturingLambda = [data]{ cout << "Data = " << data << endl;}
const int data = 234; // the captured value is const
The []
is called the lambda capture block..
- 如果在[]内只是写了变量的名字,则是以值的方式捕获
编译器会把lambda表达式转换为未全名的functor(function object), 捕获的数据成为functor的数据成员。
A functor always has a implementation of the function call operator, operator()
.
For a lambda express, this function call operator is marked as const by default.
Specify the lambda expression as mutable
to modify the captured value.
Empty parameters parentheses cannot be omitted.
int data = 123;
auto capturingLambda = [data] () mutable{
data *= 2;
cout << "Data = " << data << endl;
}
Capture Example:
[=]
captures all variables by value, not recommended[&]
captures all variables by reference, not recommended[&x]
captures only x by reference and nothing else[x]
captures only x by value and nothing else[=, &x, &y]
captures by value by default, except x and y, which are captured by reference[&, x]
captures by reference by default, except x , which is captured by reference[&x, &x]
illegal, identifiers cannot be repeated[this]
captures the current object. In the lambda expression body, you can access the object without usingthis->
[*this]
captures a copy of the current object.
The complete syntax of lambda expression:
[capture_block] (parameters) mutable constexpr noexcept_specifier attributes -> return_type { body }
- capture block. how variables are captures from enclosing scope
- parameters(optional), 只有没有指定后面那些的时候才能省略
- mutable(optional)
- constexpr(optional)
- noexcept specifier(optional)
- attributes(optional)
- return type (optional)