宏“#define requires (...)”是什么意思?

What does the macro “#define requires (...)" means?

最近在看书"Elements of Programming",在源码里发现了这个宏

我在这里也发现了类似的问题,但与此完全不同。

这里有一段代码:

#define requires(...)

template<typename T>
requires(Regular(T))
void construct(T& p)
{
// Precondition: $p$ refers to raw memory, not an object
// Postcondition: $p$ is in a default-constructed state
new (&p) T();
}

我想知道“#define requires(...)”是什么意思,为什么要这样写

这是一种'fancy'发表评论的方式。 运行 通过预处理器后,代码如下所示:

template<typename T>

void construct(T& p)
{


new (&p) T();
}

如果他们写道:

也许会更清楚
#define requires(this_doesnt_appear_to_the_right_so_the_result_is_nothing)

但这有点log-winded和迂腐。

这是某人定义pre-requisites的方式。 define 创建一个宏,该宏可以接受任意数量的参数并且不会产生任何代码。然后,他们使用自己的术语来指定所需的要求。

他们可能打算在将其添加到 c++ 时使用它来支持概念或其他一些合同系统

#define requires(...)

扩展到无。

技术:省略号...让这个宏接受可变数量的参数,这对于直接使用以逗号作为参数的模板表达式是必要的。

它显然是用来表示对模板的要求,比如未来的 C++“概念”。然而,小写名称很容易与其他东西发生冲突(宏不考虑作用域),并且如果或当 C++ 获得概念支持时,使用它的代码无论如何都必须是 double-checked,因此它有一些严重的缺点并且没有优于普通 评论.

本书Elements of Programming由STL之父Alexander Stepanov和Paul McJones合着

requires 表示法在第 1 章中描述。当前必要的实现——#define requires(...) 宏——在附录 B.2 中描述。其在书中所代表的语义描述见第13页(省略两个脚注):

An abstract procedure is parameterized by types and constant values, with the requirements on those parameters. We use function templates and function object templates. The parameters follow the template keyword and are introduced by typename for types and int or another integral type for constant values. Requirements are specified via the requires clause, whose argument is an expression built up from constant values, concrete types, formal parameters, applications of type attributes and type functions, equality of values and types, concepts, and logical connectives7.

Here is an example of an abstract procedure:

template<typename Op>
    requires(BinaryOperation(Op))
Domain(Op) square(const Domain(Op)& x, Op op)
{
    return op(x, x);
}

BinaryOperation 的概念在 p31 上定义。 Domain(Op) 的概念在第 12 页介绍。

requires 的空宏是必要的,因为 C++ 还没有完全实现它所需的支持。因此,目前它只是一个文档辅助工具,不是 C++ 编译器可以执行的操作。但毫无疑问,C++17 将更接近于能够处理它。

这本书很有趣,但也很紧凑,有时很难理解。