【发布时间】:2020-05-13 03:00:19
【问题描述】:
我正在寻找一种方法来从模板函数中的其他 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 产生 true?
以这段代码为例:
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?
【问题讨论】:
-
如果您只关心非模板 lambda,您可以使用 SFINAE 检查转换为函数指针 (
+lambda) 的格式是否正确。 -
@HolyBlackCat 我想过,但据我记得,MSVC 不允许这样做,因为它们重载了转换运算符。
-
@GuillaumeRacicot MS 为所有可用的调用约定公开了一个单独的转换运算符。只需选择一个并尝试将 lambda 转换为可比较的函数指针,然后检查是成功还是失败。
-
+似乎可以工作 here。