3

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++?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Or make the lambda receive a parameter of type A, although that's not particularly more elegant.
Jake, so the only way is to pass it as an argument or to make visible? It's so sad, I thought that it's possible to do like in JS.
That would require you to call it like test.func(test) which reminds me too much of me trying to mimic OOP in C lol.
And is it going to work fine if I have an array: A a[10]; for (int i = 0; i < 10; i++) a[i].func = [a[i]](){ a[i].x=5;};
@Artem: Well I'm certain that 'this' is not in scope outside of a member function definition and that it would be an error to use it elsewhere. I'm also certain that if you want to avoid 'test.func(test)' you either have to capture the variable or partially apply it using std::bind. either way you don't get 'this'
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.