如何在没有 std::function 和 auto 的情况下定义 lambda 表达式?

Liu*_*ibo 2 c++ lambda c++11

我已经阅读了“Effective Modern C++”的 item31 和http://en.cppreference.com/w/cpp/language/lambda 的网页,想知道我是否可以通过它的确定类型而不是包装类型来定义 lambda std::function 或关键字 ofauto以及如何实现。

例如,对于类型int

auto x_1 = 5; // type deduction
int x_2 = 5;  // defined by definite type
// both x_1, x_2 are int variables of value 5
Run Code Online (Sandbox Code Playgroud)

现在,当问题出现在 lambda 上时:

auto f_1_0 = []()->int{return 5;};
std::function<int(void)> f_1_1 = []()->int{return 5;};
SomeType f_2 = []()->int{return 5;}; // what's the SomeType here?
Run Code Online (Sandbox Code Playgroud)

Jiv*_*son 7

每个 lambda 表达式都有自己独特的类型。

这里的表达式 f_1 和 f2 有不同的类型。

auto f_1 = []()->int {return 5; }; 
auto f_2 = []()->int {return 5; }; 
Run Code Online (Sandbox Code Playgroud)

分配 f_2 = f_1 是非法的。

标准说这些类型是“未命名的”。实际上,编译器可能会为每个 lambda 组成一个新的隐藏类型名。Visual C++17 给了它们以下名称。

classmain::<lambda_7e9d7fb093569d78a8c871761cbb39d7>
classmain::<lambda_8f061a3967cd210147d6a4978ab6e125>
Run Code Online (Sandbox Code Playgroud)

不是很有用的信息。