gpt4 book ai didi

c++ - 将 lambda 仿函数编译时转换为函数指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:35 25 4
gpt4 key购买 nike

正如我们所知,非捕获 lambda 仿函数可以在运行时转换为函数指针,但编译时呢?也就是说,是否有可能类似于下面的代码?请不要提出解决方法,例如将 lambda 仿函数作为函数参数传递,我想知道更多 C++11 标准在哪里/如何禁止这样做。

template <void(*fptr)()>
void f()
{
// do something
}

int main()
{
auto l([]{});

f<(void(*)())(decltype(l))>();

return 0;
}

gcc-4.8 的强制性错误:

c.cpp: In function 'int main()':
c.cpp:11:7: error: parse error in template argument list
f<(void(*)())(decltype(l))>();
^
c.cpp:11:36: error: statement cannot resolve address of overloaded function
f<(void(*)())(decltype(l))>();
^

最佳答案

Lambda 表达式,即使有一个空闭包,也不能用作指向函数模板参数的指针,因为它们是临时变量,只是碰巧转换为某个指向函数的指针。根据 5.1.2 [expr.prim.lambda] 第 2 段,lambda 表达式是临时的:

The evaluation of a lambda-expression results in a prvalue temporary. [...]

第 6 段中描述了到函数指针的转换:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

也就是说,转换不会产生 constexpr,因此,没有希望将生成的指针用作模板参数。

至于原因,我目前能找到的最好的是 N3597 中的声明。指向N2895这似乎在谈论实际问题,但我找不到详细的讨论。似乎 lambda 表达式创建的函数的名称重整是禁止在某些上下文中使用它们的问题之一。

关于c++ - 将 lambda 仿函数编译时转换为函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673004/

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