0

I'm trying to add all items in one list to another using the first list's forEach method that takes a function pointer and calls the function on each element, but I'm having trouble creating a function pointer that can call the second list's member functions. I've tried using lambdas:

LinearLinkedList<bar> test;
//<add items to test>
LinearLinkedList<bar> sorted;
auto addToSorted = [&](bar * b) { sorted.addSorted(b, &barLessThan); };
test.forEach(&addToSorted);

and using an inner struct:

LinearLinkedList<bar> test;
//<add items to test>
LinearLinkedList<bar> sorted;
struct Sorter {
    static LinearLinkedList<bar> * list = &sorted;
    static void addToSorted(bar * b) { list->addSorted(b, &barLessThan); }
};
test.forEach(&Sorter::addToSorted);

but both are rejected by the compiler because they reference sorted in an illegal way. How can I reference sorted in a call to forEach?

Vitruvie
  • 2,327
  • 18
  • 25

1 Answers1

0

Lambdas can decay to function pointers only if they don't capture anything. Consider the following snippet:

#include <iostream>

void run(int(*f)())
{
    std::cout << f();
}

struct S {
    static int something;
    static int nothing()
    {
        return something;
    }
};
int S::something = 0;

int main()
{
    auto simpleLambda = [](){ return 1; };
    run(simpleLambda);

    // auto capturingLambda = [&](){ return 1; };
    // run(capturingLambda);

    S::something = 2;
    run(S::nothing);
}

The commented out section won't compile because the capturingLambda has a non-empty capture list. You can use the workaround I put in the code, or better yet make your forEach function templated on the functor type as all of the STL algorithms do.

Rostislav
  • 3,857
  • 18
  • 30
  • This question isn't necessarily about lambdas. Is the lesson here that there's no way for a function pointer to have a reference to non-global variables? – Vitruvie Oct 13 '15 at 02:35
  • @Saposhiente I see. Well, if you think about it, a function pointer only has access to its parameters and data with static storage duration. So unless you put your local data to either of those, the function (accessed through function pointer) won't have access to it. [Here](http://stackoverflow.com/a/13238113/3589890) there's a kind of cleaner workaround, but the idea is still the same you can't get access to non-static-storage-duration data from within a free function. – Rostislav Oct 13 '15 at 11:39