如何使lambda成为类的朋友? [英] How to make the lambda a friend of a class?
本文介绍了如何使lambda成为类的朋友?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个类:
class A {
int a;
};
我有一个lambda:
And I have a lambda:
auto function = [](A* a) {
a->a; // <== gives an error in this line.
};
function(new A);
有什么办法在lambda中使用私有成员/方法? - 没有必要将指针传递给lambda - 它可能是一个捕获或其他。
Is there any way to use a private member/method inside a lambda? - It's not necessary to pass the pointer to the lambda - it may be a capture-by or something else.
欢迎所有合理的方案。
推荐答案
你可以通过创建一个返回lambda函数的friend函数来实现。它继承了朋友访问:
You can do it by creating a friend function that returns the lambda function. It inherits the friend access:
struct A {
friend std::function<void(A&, int)> f();
private:
int i;
void test() {std::cout << "test: " << i << "\n";}
};
std::function<void(A&, int)> f() {
return [] (A &a, int i) {a.i = i; a.test(); };
}
int main() {
A a;
f()(a, 13);
return 0;
}
这篇关于如何使lambda成为类的朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文