当我们有函数和 lambda 时,"blocks" 在 C++ 中有什么用?

What are "blocks" used for in C++ when we have functions and lambdas?

我发现了这个奇怪的结构,它显然来自 C,并被 Objective-C 和 C++(作为扩展)采用。甚至还有 new development for it in clang。当我看到这个时我真的很惊讶,我从来没有见过有人用过这个。

根据规范,您似乎可以使用以下语法声明 "blocks":

// Declaration
int (^x)(char);
void (^z)(void);
int (^(*y))(char) = &x;

// Invocation
x('a');
(*y)('a');
(true ? x : *y)('a')

块中的所有变量都是常量类型的。为什么这有用?

A Block that referenced these variables would import the variables as const variations.

我什至找不到 C++ 标准中的块(在 cppreference 上)。有没有人知道这些为什么存在以及它们的用途的任何链接或历史背景?

注意:我已经很清楚这是一个 C++ 扩展,clang 可能支持它。我的问题仍然存在 - 为什么我们需要这个?

对于 block,这是 Objective-C(或 Objective-C++),相当于 C++ 中的 lambda。例如,块

int (^sqr)(int) = ^(int x) {return x*x};

在 C++ 中可能如下所示:

auto sqr = [](int x) {return x*x;}

clang 同时支持 Objective-C 和 Objective-C++。