Function returning a lambda expression

后端 未结 6 1886
猫巷女王i
猫巷女王i 2020-11-29 18:24

I wonder if it\'s possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but th

6条回答
  •  隐瞒了意图╮
    2020-11-29 19:12

    Though the question specifically asks about C++11, for the sake of others who stumble upon this and have access to a C++14 compiler, C++14 now allows deduced return types for ordinary functions. So the example in the question can be adjusted just to work as desired simply by dropping the -> decltype... clause after the function parameter list:

    auto retFun()
    {
        return [](int x) { return x; }
    }
    

    Note, however, that this will not work if more than one return ; appears in the function. This is because a restriction on return type deduction is that all return statements must return expressions of the same type, but every lambda object is given its own unique type by the compiler, so the return ; expressions will each have a different type.

提交回复
热议问题