Question

I've just rewritten the following C89 code, that returns from the current function:

// 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;
            }
        }
    }
}

With this C++0x STL/lambda hybrid:

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;
        }
    }});

Which generates:

1>e:\src\cpfs4\libcpfs\inode.cc(128): error C3499: a lambda that has been specified to have a void return type cannot return a value

I hadn't considered that the return in the lambda, doesn't actually return from the caller (having never seen a scoped function in C/C++ before now). How do I return true from the caller where the original function would have done so?

Was it helpful?

Solution

You don't; std::for_each isn't structured to handle an early return. You could throw an exception...

Or don't use a lambda:

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

OTHER TIPS

Use std::find_if() instead of std::for_each():

if (std::find_if(g_cpfs->htab.begin(), g_cpfs->htab.end(),
        [inode](Handle const &handle) {
            if (handle.valid() && handle.ino == inode->ino) {
                log_info("Inode "INO_FMT" is still open, delaying removal.",
                    inode->ino);
                return true;
            }
            return false;
        }) != g_cpfs->htab.end()) {
    return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top