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*)'
CodePudding user response:
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.