I want to do the equivalent of the following python code:
class A:
def__init__(self):
self.f = None
class B:
def __init__(self, s, a): # s will be a string a will be an A.
self.s = s
a.f = lambda : self._s
a = A()
b = B('this is b", a)
print(a.f())
outputs:
this is b
w/o showing all the C++ code, I get an error
error: cannot convert 'C::C(std::__cxx11::string, A)::<lambda()>' to 'std::__cxx11::string (*)() {aka st
d::__cxx11::basic_string<char> (*)()}' in assignment
a.f = [this]()->std::string {return this->name;};
From an answer to a related question, I see that the type of the lambda function is unique and therefore the assignment fails. Is there a way to make this work?
struct A {
std::string (*f)(); };
struct B {
std::string name;
B(std::string n, A& a)
: name(n)
{
a.f = [this]()->std::string {return this->name;};
} };
int main() {
A a;
B b("this is b", a);
cout << a.f() << endl; }
Edited version with std::function fails with std::bad_function_call
struct A {
std::function<std::string ()> f;
};
struct B {
std::string name;
B(std::string n, A& a)
: name(n)
{
std::function<std::string ()> f = [this]()->std::string {return this->name;};
a.f = f;
}
};
int main()
{
A a;
B b("this is b", a);
std::cout << a.f() << std::endl;
}
Outputs:
this is b