问题描述
是否有一种方法可以使lambda衰减到指针,而无需显式转换为正确的签名?这样可以整理一些代码:
Is there a way to make a lambda decay to a pointer, without explicitly casting to the right signature? This would tidy some code:
template<typename T> T call(T(*func)()){ return func(); }
int ptr(){ return 0; }
int main(){
auto ret1 = call(ptr);
auto ret2 = call((int(*)())([]{ return 0; }));
auto ret3 = call([]{ return 0; }); //won't compile
}
很明显,仅当lambda衰减到指针时,对call
的调用才有效,但是我猜测只有在选择了正确的函数重载/模板之后,这种情况才会发生.不幸的是,我只能想到涉及模板的解决方案,以使λ具有任何签名衰减,所以我回到正题.
It's evident that a call to call
works only if the lambda decays to a pointer, but I'm guessing that that can happen only after the right function overload/template is chosen. Unfortunately I can only think of solutions that involve templates to make a lambda with any signature decay, so I'm back to square one.
推荐答案
您可以将lambda更改为使用一元+
运算符:+[]{ return 0; }
You can change your lambda to use the unary +
operator: +[]{ return 0; }
之所以可行,是因为一元加号可以应用于指针,并且会触发对函数指针的隐式转换.
This works because unary plus can be applied to pointers, and will trigger the implicit conversion to function pointer.
这篇关于传递给模板函数时,lambda自动衰减为函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!