Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot convert 'LinkedList::filter(void (*)(Node*))::<lambda(Node*)>' to 'void (*)(Node*)'

Im trying to implement a simple LinkedList class, but this error shows up and I don’t understand why.

struct Node {
public:
    int val;
    Node* next;
    Node(int v) : val(v), next(nullptr) {}
};

struct LinkedList {
public:
    Node* head;
    Node* tail;
    LinkedList() : head(nullptr), tail(nullptr) {}

    void append(int value) {
        Node* new_node = new Node(value);
        if (head == nullptr) {
            head = new_node;
            tail = new_node;
        } else {
            tail->next = new_node;
            tail = new_node;
        }
    }

    void traverse(void (*callback)(Node* node)) {
        Node* cur = head;
        while (cur != nullptr) {
            callback(cur);
            cur = cur->next;
        }
    }

    LinkedList filter(bool (*filter_function)(Node* node)) {
        LinkedList new_list = LinkedList();
        traverse([&](Node* node) { if(filter_function(node)) new_list.append(node->val); });
        return new_list;
    }
};

error is in this line

traverse([&](Node* node) { if(filter_function(node)) new_list.append(node->val); });

cannot convert 'LinkedList::filter(void (*)(Node*))::<lambda(Node*)>' to 'void (*)(Node*)'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As mentioned in the comments, a capturing lambda is not the same as a function pointer. Instead, behind the scenes, it is a fully-fledged object (because it has state).

Fortunately, there’s an easy fix – you can use the magical powers of std::function to abstract away all the messy details. To do this, all you have to do is #include <functional> and change this:

void traverse(void (*callback)(Node* node)) {

to this:

void traverse (std::function <void (Node* node)> callback) {

and you are golden.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading