lambda是否应该在模板代码中的函数指针? [英] Should lambda decay to function pointer in templated code?

查看:114
本文介绍了lambda是否应该在模板代码中的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到某个地方,lambda函数应该衰减到函数指针,如果捕获列表为空。我现在可以找到的唯一参考是 n3052 < a>。除非在模板代码中声明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是否应该在模板代码中的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆