[英]How can I make a function pointer that references a local variable?
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. 我试图使用第一个列表的
forEach
方法将一个列表中的所有项目添加到另一个列表中,该方法采用一个函数指针并在每个元素上调用该函数,但是我在创建可以调用第二个列表的成员函数的函数指针时遇到了麻烦。 I've tried using lambdas: 我试过使用lambda:
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
: 并使用内部
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. 但两者都被编译器拒绝,因为他们引用
sorted
以非法方式。 How can I reference sorted
in a call to forEach
? 如何在调用
forEach
引用sorted
?
Lambdas can decay to function pointers only if they don't capture anything. 仅当Lambda不捕获任何内容时,它们才能衰减为函数指针。 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. 带注释的部分将不会编译,因为
capturingLambda
具有非空的捕获列表。 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. 您可以使用我在代码中放入的解决方法,或者更好地使您的
forEach
函数像所有STL算法一样,以forEach
函数为模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.