I am trying to make a class function take another class unknown function. I hope that made any sense. What I am trying to do is… if button1 (or any declared button) is clicked, it will execute whatever function (any “void function”) that was inputted into the first parameter of function Event__MouseClicked.
bool MouseClicked( void ){ /**/ };
namespace XE
{
class Window
{
public:
const char* Title;
};
class Button
{
public:
void Event__MouseClicked( void( *Function )( void ) ) {
if( MouseClicked( ) )
( *Function )( );
}
};
};
class XorrWindow1 : public XE::Window
{
public:
XorrWindow1( void ) {
Initialize( );
}
protected:
~XorrWindow1( void );
private:
XE::Button Button1;
XE::Button Button2;
private:
// EVENT PROTOTYPES
void DoSomething( void );
void RandomFunction( void );
void Initialize( void )
{
// INITIALIZE CONTROLS
// AND OTHER STUFF BELOW
this->Title = "XorrWindow1";
// How can I resolve this problem?
this->Button1.Event__MouseClicked( &XorrWindow1::DoSomething );
this->Button2.Event__MouseClicked( &XorrWindow1::RandomFunction );
};
};
void XorrWindow1::DoSomething( void ) {
::MessageBoxA( NULL, this->Title, "Button1 clicked!", MB_OK );
};
void XorrWindow1::RandomFunction( void ) {
::MessageBoxA( NULL, this->Title, "Button2 clicked!", MB_OK );
};
The error is this:
'XE::Button::Event__MouseClicked' : cannot convert parameter 1 from 'void (__thiscall XorrWindow1::* )(void)' to 'void (__cdecl *)(void)'
I absolutely understand what caused the error. But I don’t know how to fix it because it must be able to take any unknown function of class Window1.
Like Karel Petranek said, you need templates to accommodate all cases. Here is the most generic method (utilized by STL everywhere):
Basically
Event__MouseClickedaccepts a callable object. In your case you would call it like Marcelo Cantos described:But the benefit of this method is that passing any callable object that takes no arguments into
Event__MouseClickedwill compile and work. You can pass a function pointer, the result ofstd::bind, astd::function, a lambda, etc etc.This is more optimal than forcibly accepting a
std::functionin some cases, for example when accepting a straight function pointer.