直接从C++ 0x lambda调用者返回

Mat*_*ner 5 c++ lambda return-type c++11

我刚刚重写了以下C89代码,它从当前函数返回:

// make sure the inode isn't open
{
    size_t i;
    for (i = 0; i < ARRAY_LEN(g_cpfs->htab); ++i)
    {
        struct Handle const *const handle = &g_cpfs->htab[i];
        if (handle_valid(handle))
        {
            if (handle->ino == (*inode)->ino)
            {
                log_info("Inode "INO_FMT" is still open, delaying removal.",
                        (*inode)->ino);
                return true;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此C++ 0x STL/lambda混合:

std::for_each(g_cpfs->htab.begin(), g_cpfs->htab.end(), [inode](Handle const &handle) {
    if (handle.valid()) {
        if (handle.ino == inode->ino) {
            log_info("Inode "INO_FMT" is still open, delaying removal.", inode->ino);
            return true;
        }
    }});
Run Code Online (Sandbox Code Playgroud)

哪个产生:

1> e:\ src\cpfs4\libcpfs\inode.cc(128):错误C3499:已指定具有void返回类型的lambda无法返回值

我没有考虑过lambda中的返回,实际上并没有从调用者返回(之前从未见过C/C++中的作用域函数).我如何return true从原始函数的调用者那里做到这一点?

小智 6

你没有; std :: for_each的结构不适合处理早期返回.你可以抛出异常......

或者不要使用lambda:

for (auto const &handle : g_cpfs->htab) {
  // code that was in lambda body
}
Run Code Online (Sandbox Code Playgroud)