Should lambda decay to function pointer in templated code?

浪尽此生 提交于 2019-12-10 02:36:50

问题


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) = []{};
}

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

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

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?


回答1:


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

I also tried a few other things:

template <class T>
void foo(void (*f)(void)) {}

foo<int>([]{});

That works.

typedef void (*fun)(void);

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

foo<int>()();

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

Note: I only tested in g++ 4.5.



来源:https://stackoverflow.com/questions/3155869/should-lambda-decay-to-function-pointer-in-templated-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!