1

Having trouble to call an event handler directly from my code. I found the same question 2 years ago here. original question

But the line me_InsertCommentText(wxCommandEvent()); is not compiling (mingw32-gcc 4.8, win7, codeblocks, wxFormBuilder)

error: no matching function for call to 'mjpgen_wdDialog::me_InsertCommentText(wxCommandEvent)' note: candidate is: note: void mjpgen_wdDialog::me_InsertCommentText(wxCommandEvent&)

For me that appears to be caused by the calling by reference parameters. How can I get this to work?

Community
  • 1
  • 1
ahagele
  • 69
  • 1
  • 6

2 Answers2

2

The answer about using a named temporary variable is technically correct, but the important thing is that you really shouldn't be doing this in the first place. The handlers are only supposed to be called from wxWidgets and instead of calling some OnFoo(wxFooEvent&) directly you should refactor your code to just call some new DoFoo() from OnFoo() and then call DoFoo() from the rest of your code if you need it.

This becomes even simpler when using C++11 as you don't even need to have OnFoo() at all in this case and could just write

whatever->Bind(wxEVT_FOO, [=](wxCommandEvent&) { DoFoo(); });

to avoid an extra function.

VZ.
  • 21,740
  • 3
  • 39
  • 42
  • Sure that is a tidy way but would require to rework every event handler as soon as it needs to be called directly. – ahagele May 03 '16 at 22:50
  • I'm not familiar with the bind template. Not sure how that will work with the event handler code generated by wxFormBuilder. It generates a virtual method for the event handler. – ahagele May 03 '16 at 22:57
  • It doesn't matter whether an event handler is virtual or not and I'm not really sure why do you think it does? – VZ. May 04 '16 at 14:13
1

wxCommandEvent() is a temporary object, which couldn't be bound to non-const reference. You could use named variable here:

wxCommandEvent event;
me_InsertCommentText(event);

or change the type of parameter to const reference:

void mjpgen_wdDialog::me_InsertCommentText(const wxCommandEvent&)

then

me_InsertCommentText(wxCommandEvent());
songyuanyao
  • 169,198
  • 16
  • 310
  • 405