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) {
                } else {
                    if (!objectsToDelete.contains(child->id())) {
        } else {

    for (ContentObject *contentObj : d->contentObjects.values()) {
        if (contentObj->isSelected()) {

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: