贯穿 C++ 11 与 C++ 17 的 Lambda 到底是个什么?
置顶/星标公众号👇,硬核文章第一时间送达!
1
什么是Lambda函数?
[ capture list ] (parameters) -> return-type
{ method definition
}
2
为什么我们要使用Lambda函数?
struct print
{
void operator()(int element)
{
cout << element << endl;
}
};
int main(void)
{
std::vector<int> v = {1, 2, 3, 4, 5};
std::for_each(v.begin(), v.end(), print());
return 0;
}
std:for_each(v.begin(), v.end(), [](int element) { cout << element << endl; });
3
Lambda函数内部是如何工作的?
[&i] ( ) { std::cout << i; }
// is equivalent to
struct anonymous
{
int &m_i;
anonymous(int &i) : m_i(i) {}
inline auto operator()() const
{
std::cout << i;
}
};
4
使用Lambda函数的好处
5
学习Lambda表达式
int main()
{
int x = 100, y = 200;
auto print = [&] { // Capturing object by reference
std::cout << __PRETTY_FUNCTION__ << " : " << x << " , " << y << std::endl;
};
print();
return 0;
}
main()::<Lambda()> : 100 , 200
6
Lambda函数的捕获列表
template <typename Functor>
void f(Functor functor)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
/* Or alternatively you can use this
void f(std::function<int(int)> functor)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
*/
int g() { static int i = 0; return i++; }
int main()
{
auto Lambda_func = [i = 0]() mutable { return i++; };
f(Lambda_func); // Pass Lambda
f(g); // Pass function
}
Function Type : void f(Functor) [with Functor = main()::<Lambda(int)>]
Function Type : void f(Functor) [with Functor = int (*)(int)]
class Example
{
public:
Example() : m_var(10) {}
void func()
{
[=]() { std::cout << m_var << std::endl; }(); // IIFE
}
private:
int m_var;
};
int main()
{
Example e;
e.func();
}
7
C++的Lambda函数类型
const auto l = [](auto a, auto b, auto c) {};
// is equivalent to
struct anonymous
{
template <class T0, class T1, class T2>
auto operator()(T0 a, T1 b, T2 c) const
{
}
};
void print() {}
template <typename First, typename... Rest>
void print(const First &first, Rest &&... args)
{
std::cout << first << std::endl;
print(args...);
}
int main()
{
auto variadic_generic_Lambda = [](auto... param) {
print(param...);
};
variadic_generic_Lambda(1, "lol", 1.1);
}
[]() mutable {}
// is equivalent to
struct anonymous
{
auto operator()() // call operator
{
}
};
#include <iostream>
#include <type_traits>
int main()
{
auto funcPtr = +[] {};
static_assert(std::is_same<decltype(funcPtr), void (*)()>::value);
}
const auto less_than = [](auto x) {
return [x](auto y) {
return y < x;
};
};
int main(void)
{
auto less_than_five = less_than(5);
std::cout << less_than_five(3) << std::endl;
std::cout << less_than_five(10) << std::endl;
return 0;
}
8
constexpr Lambda表达式
constexpr auto sum = [](const auto &a, const auto &b) { return a + b; };
/*
is equivalent to
constexpr struct anonymous
{
template <class T1, class T2>
constexpr auto operator()(T1 a, T2 b) const
{
return a + b;
}
};
*/
constexpr int answer = sum(10, 10);
9
结束语
关注公众号「高效程序员」👇,一起优秀!
评论