Artem
Artem

Reputation: 119

Is it possible to create lambda methods of a particular class?

For instance I have

class A {
public:
    int x, y;
    int(*func)();
};

and I would like to make that func be something like

int main()
{
    A a;
    a.func = [this](){return x + y;};
}

or something like that. That would mean that I can create method "func" during runtime and decide what it is. Is it possible in C++?

Upvotes: 3

Views: 109

Answers (1)

Jake
Jake

Reputation: 757

It is sorta possible but only using captures which would mean you would need to use std::function<> instead. It wont have nice 'this' behavior like you wanted I think

struct A {
  int x, y;
  std::function<int()> func;
};

and then code like this

int main() {
    A self;
    test.func = [&self](){ return self.x + self.y; };
}

I never say never in C++ (even with goto) but I'm rather unsure that this would actually be a good way to do things. Yes, you CAN do this but are you sure there isn't a better way? Food for thought.

Upvotes: 1

Related Questions