Tag Archives: c++

Recursive lambda functions

Today i found out how to use lambda functions in a recursive manner. Documentation from std::function states:

Instances of std::function can store, copy, and invoke any callable target — functions, lambda expressions, bind expressions, or other function objects.

It can’t get easier than that!
So here’s an example taken from some code I had to do which uses lambda functions recursivly to delete contents on a device.

#include <functional>

void MtpDevice::deleteSelectedFiles()
{
    QStringList objectsToDelete;

    std::function<void(ContentObject*)> addChildren;
    addChildren = [&addChildren, &objectsToDelete] (ContentObject *obj) -> void {
        if (obj->type() == ContentObject::FOLDER) {
            for (ContentObject *child : obj->children()) {
                if (child->type() == ContentObject::FOLDER) {
                    addChildren(child);
                    objectsToDelete.append(child->id());
                } else {
                    if (!objectsToDelete.contains(child->id())) {
                        objectsToDelete.append(child->id());
                    }
                }
            }
        } else {
            objectsToDelete.append(obj->id());
        }
    };


    for (ContentObject *contentObj : d->contentObjects.values()) {
        if (contentObj->isSelected()) {
            addChildren(contentObj);
            objectsToDelete.append(contentObj->id());
        }
    }

    for (const QString &objId : objectsToDelete) {
        deleteContent(objId);
    }
}
Tagged ,