我试图创建一个类,在构造函数中将一个lambda函数作为参数,我希望这个函数成为类的朋友.该类的代码如下所示:
using func = std::function<void(void)>;
class foo
{
public:
foo(func f)
{
this->f = f;
}
func f;
private:
int value_I_want_to_modify; //an int I want to change from the function I've passed in the constructor
}
在main()中我会写这样的东西:
int main()
{
//this will give an error because I cannot access private members from outside class
foo v
{
[&v](void) { v.value_I_want_to_modify = 0 };
}
}
现在我希望函数成为该类的朋友,但我找不到办法.
解决方法:
How to make a lambda function friend of a class?
你不能.这是一个问题22.
如果在定义类之前定义lambda函数,则无法访问类的成员变量.
using func = std::function<void(void)>;
class foo;
// Trying to define the lambda function before the class.
// Can't use f.value_I_want_to_modify since foo is not defined yet.
auto lambda_function = [](foo& f) { f.value_I_want_to_modify = 0;}
class foo
{
public:
foo(func f)
{
this->f = f;
}
func f;
private:
int value_I_want_to_modify;
};
int main()
{
foo v{lambda_function};
}
如果在定义类之后定义lambda函数,则不能使lambda函数成为类的朋友.
using func = std::function<void(void)>;
class foo
{
public:
foo(func f)
{
this->f = f;
}
func f;
private:
int value_I_want_to_modify;
};
int main()
{
foo f
{
// Can't make the lambda function a friend of foo
// since it cannot be declared before the class definition.
[&f](void) { f.value_I_want_to_modify = 0;}
}
}
最简单的解决方法是修改lambda函数以接受int&作为参数并修改其值.
#include <functional>
using func = std::function<void(int&)>;
class foo
{
public:
foo(func f)
{
this->f = f;
this->f(value_I_want_to_modify);
}
private:
func f;
int value_I_want_to_modify;
};
int main()
{
foo v{ [](int& out) { out = 0;} };
}