std::function & lambda expression

日月星辰 发布在Programming

std::function

std::function<functional> 头文件中定义的,创建的类型可以指向任何可以被调用的:

std::function is called a polymorphic function wrapper. 可以用作函数指针或是作为函数的参数实现回调。

std::function的模板语法如下:

std::function<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..

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:

The complete syntax of lambda expression:

[capture_block] (parameters) mutable constexpr noexcept_specifier attributes -> return_type { body }