Menu

#44 same event name for different events does not compile using

open
nobody
None
5
2010-12-23
2010-12-23
No

What steps will reproduce the problem? 1. Create two elements (gamma and gradient) in the same frame or panel, with different kind of events (example: a checkbox (commandEvent) and a spinctrl (spinEvent) ) 2. Since you want to update something when either of those values change you call the respective event the same: OnSpinCtrl → OnChange and OnCheckbox → OnChange 3. Create C++ Code and compile it using GCC 4.4 (standard compiler on Ubuntu)

What is the expected output? What do you see instead? Expected: Well it should work! Instead GCC 4.4 throws following error: error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘void (wxEvtHandler::*)(wxSpinEvent&)’ or error: invalid static_cast from type ‘<unresolved overloaded function type>’ to type ‘void (wxEvtHandler::*)(wxCommandEvent&)’

for following lines respectively:

gamma→Connect( wxEVT_COMMAND_SPINCTRL_UPDATED, wxSpinEventHandler( ImproveContoursSidebar_::OnChange ), NULL, this ); gradient→Connect( wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( ImproveContoursSidebar_::OnChange ), NULL, this );

Problem: The function OnChange is overloaded for either event. Passing the function pointer does not tell the compiler which one of the functions to use. The macros wxSpinEventHandler and wxCommandEventHandler would later cast those function pointers to ‘void (wxEvtHandler::*)(wxSpinEvent&)’ and ‘void (wxEvtHandler::*)(wxCommandEvent&)’ respectively.

Walkarounds: 1. Just rename the events so that there are not two types of events called the same (OnChange → OnChangeSpin, OnChangeCommand). You can still use the same event name for all the elements that actually use the same type of event. The problem is only occurring when the function is happened to be overloaded.

2. Save the function pointer in a variable first (because then you have to tell the variable what type of function pointer it is) and then pass it. Problem with this walkaround: You cannot use the macros wxSpinEventHandler and wxCommandEventHandler because they take the reference of the passed argument and to save the variable you have to save the reference of the function pointer already and so the macro will create a reference to the reference to the function which will result in another invalid static cast.

Discussion