gpt4 book ai didi

c++ - 如何使 lambda 函数成为类的友元?

转载 作者:太空狗 更新时间:2023-10-29 20:21:43 27 4
gpt4 key购买 nike

我试图创建一个在构造函数中将 lambda 函数作为参数的类,并且我希望此函数与该类成为 friend 。该类的代码如下所示:

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

现在我希望该函数与类成为 friend ,但我找不到实现它的方法。

最佳答案

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

关于c++ - 如何使 lambda 函数成为类的友元?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41813049/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com