如何制作引用局部变量的函数指针?

How can I make a function pointer that references a local variable?

我正在尝试使用第一个列表的 forEach 方法将一个列表中的所有项目添加到另一个列表中,该方法采用函数指针并在每个元素上调用该函数,但我在创建函数时遇到了问题可以调用第二个列表的成员函数的指针。我试过使用 lambdas:

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

并使用内部 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);

但两者都被编译器拒绝,因为它们以非法方式引用 sorted。如何在调用 forEach 时引用 sorted

只有当 Lambda 不捕获任何内容时,它们才能退化为函数指针。考虑以下片段:

#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);
}

注释掉的部分不会编译,因为 capturingLambda 有一个非空的捕获列表。您可以使用我放在代码中的解决方法,或者更好的是让您的 forEach 函数像所有 STL 算法一样在仿函数类型上模板化。