lambda是否应该在模板代码中的函数指针?

编程入门 行业动态 更新时间:2024-10-24 21:20:46
本文介绍了lambda是否应该在模板代码中的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我读到某个地方,lambda函数应该衰减到函数指针,如果捕获列表为空。我现在可以找到的唯一参考是 n3052 。除非在模板代码中声明lambda。

I read somewhere that a lambda function should decay to function pointer if the capture list is empty. The only reference I can find now is n3052. With g++ (4.5 & 4.6) it works as expected, unless the lambda is declared within template code.

例如,下面的代码编译:

For example the following code compiles:

void foo() { void (*f)(void) = []{}; }

但是当模板化时不再编译> foo 实际上在其他地方调用):

But it doesn't compile anymore when templated (if foo is actually called elsewhere):

template<class T> void foo() { void (*f)(void) = []{}; }

在上面的参考中,我没有看到这种行为的解释。这是g ++的临时限制,如果没有,是否有一个(技术)原因不允许这样?

In the reference above, I don't see an explanation of this behaviour. Is this a temporary limitation of g++, and if not, is there a (technical) reason not to allow this?

推荐答案

可以想到没有理由,它将被明确禁止。我猜这只是g ++的暂时限制。

I can think of no reason that it would be specifically disallowed. I'm guessing that it's just a temporary limitation of g++.

我也尝试了其他几个:

template <class T> void foo(void (*f)(void)) {} foo<int>([]{});

可以工作。

typedef void (*fun)(void); template <class T> fun foo() { return []{}; } // error: Cannot convert. foo<int>()();

这不是(但如果 foo 未参数化)。

That doesn't (but does if foo is not parameterized).

注意:我只在g ++ 4.5中测试。

Note: I only tested in g++ 4.5.

更多推荐

lambda是否应该在模板代码中的函数指针?

本文发布于:2023-11-14 02:58:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   函数   模板   代码   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!