gpt4 book ai didi

c++ - 标准是否保证无捕获 lambda 为空?

转载 作者:行者123 更新时间:2023-12-01 11:54:32 24 4
gpt4 key购买 nike

我正在寻找一种方法来从模板函数中的其他 lambda 中识别空的(无捕获的)lambda。我目前正在使用 C++17,但我也对 C++20 的答案感到好奇。

我的代码如下所示:

template<typename T>
auto func(T lambda) {
// The aguments of the lambdas are unknown

if constexpr (/* is captureless */) {
// do stuff
}
}

C++ 标准(17 或 20)是否保证可转换为函数指针的无捕获 lambda 也会使 std::is_empty 产量真的吗?

以这段代码为例:
auto a = []{}; // captureless
auto b = [c = 'z']{}; // has captures

static_assert(sizeof(a) == sizeof(b)); // Both are the same size
static_assert(!std::is_empty_v<decltype(b)>); // It has a `c` member
static_assert(std::is_empty_v<decltype(a)>); // Passes. It is guaranteed?

Live example

最佳答案

不,事实上,标准明确授予 lambda 的权限,使其具有与其声明不一致的大小。 [expr.prim.lambda.closure]/2状态

The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression. [ Note: This determines the set of namespaces and classes associated with the closure type ([basic.lookup.argdep]). The parameter types of a lambda-declarator do not affect these associated namespaces and classes. — end note ] The closure type is not an aggregate type. An implementation may define the closure type differently from what is described below provided this does not alter the observable behavior of the program other than by changing:

  • the size and/or alignment of the closure type,

  • whether the closure type is trivially copyable ([class.prop]), or(2.3)

  • whether the closure type is a standard-layout class ([class.prop]).

An implementation shall not add members of rvalue reference type to the closure type.


强调我的
所以这允许实现给 lambda 一个成员,即使它是无捕获的。我认为任何实现都不会,但法律允许他们这样做。

关于c++ - 标准是否保证无捕获 lambda 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59936159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com