嵌套lambda函数

Hum*_*awi 5 c++ lambda c++11

我有以下代码:

auto get_functor = [&](const bool check) {
    return  [&](const foo& sr)->std::string {
        if(check){
            return "some string";
        }
        return "another string"
    };
};
run(get_functor(true));
Run Code Online (Sandbox Code Playgroud)

run函数签名:

void run(std::function<std::string(const foo&)> func);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误,但对我来说不太清楚:

error C2440: 'return' : cannot convert from 'main::<lambda_6dfbb1b8dd2e41e1b6346f813f9f01b5>::()::<lambda_59843813fe4576d583c9b2877d7a35a7>' to 'std::string (__cdecl *)(const foo &)'
Run Code Online (Sandbox Code Playgroud)

PS我在MSVS 2013上

编辑:

如果我通过替换auto实型来编辑代码:

std::function<std::string(const foo&)> get_functor1 = [&](const bool check) {
    return  [&](const foo& sr)->std::string {
        if (check) {
            return "some string";
        }
        return "another string";
    };
};
run(get_functor1(true));
Run Code Online (Sandbox Code Playgroud)

我收到另一个错误:

error C2664: 'std::string std::_Func_class<_Ret,const foo &>::operator
()(const foo &) const' : cannot convert argument 1 from 'bool' to
'const foo &'
Run Code Online (Sandbox Code Playgroud)

完全搞砸了!

Rer*_*ito 5

我能够使用以下MVCE在VS 2013上重现相同的错误:

#include <iostream>
#include <functional>
#include <string>

struct foo {};

std::string run(std::function<std::string(foo const&)> f) {
    return f(foo());
}

int main() {

    auto get_functor = [&](bool const check) {
        return [=](foo const&) -> std::string { // Line of the compiler error
            if (check) {
                return "CHECK!";
            }
            else {
                return "NOT CHECK!";
            }
        };
    };

    std::cout << run(std::function<std::string(foo const&)>(get_functor(true)));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后我得到错误:

Error   1   error C2440: 'return' : cannot convert from 'main::<lambda_1bc0a1ec72ce6dc00f36e05599609bf6>::()::<lambda_4e0981efe0d720bad902313b44329b79>' to 'std::string (__cdecl *)(const foo &)'
Run Code Online (Sandbox Code Playgroud)

问题在于MSVC无法处理返回的Lambda:当您不指定返回类型时,它将尝试将其衰减为常规函数指针。之所以失败,是因为您的lambda确实捕获了元素!

此外,您的解决方法是错误的,因为std::function<std::string(foo const&)>不是其类型,get_functor而是您要从中返回的类型。

强制std::function直接嵌入返回的lambda get_functor中将解决您的问题:

auto get_functor = [&](bool const check) -> std::function<std::string(foo const&)> {
    return [=](foo const&) -> std::string {
        if (check) {
            return "some string";
        } else {
            return "another string";
        }
    };
};
std::cout << run(get_functor(true));
Run Code Online (Sandbox Code Playgroud)