How to detect overwritten virtual method in base class?

M

macracan

It has been discussed before, but I still can't find a solution and I
have a need. So here goes:

The problem:
I'm writing a something to handle messages from XWindows. The idea is
to have virtual handlers for different
kind of messages. But XWindows has a feature thereby you have to
subscribe to messages you're interested in.
I was thinking of providing empty handlers by default, and overwrite
them in derived classes. And I would need
to automatically detect which virtual fcts are overwritten, so I can
tell XWindows to which message I wish to subscribe.
Somewhat like so:
struct WindowSink
{
// ...
// default empty handlers
virtual void Move(int x, int y){}
virtual void Draw(){}
};
//...
struct MyWindowSink : public WindowSink
{
// overwrite Draw only
void Draw(){ /*some different behavior*/}
};
void Subscribe(WindowSink &sink)
{
static WindowSink sinkref; // some reference to compare with
long mask = 0;
// figure out which messages to subscribe to
if (&sinkref.Move != &sink.Move) mask |= 1;
if (&sinkref.Draw != &sink.Draw) mask |= 2;

// subscribe to messages based on mask
XSelectInput(/* some other params */, mask);
}
int main()
{
MyWindodwSink sink;
//...
Enable(sink);
// ...
return 0;
}

Now as the group already knows, the lines
if (&sinkref.Move != &sink.Move) mask |= 1;
if (&sinkref.Draw != &sink.Draw) mask |= 2;
are not valid C++ code anymore.
Is there any way I can write it?

BTW, I've looked into rtti (didn't find solution), and low level non-
portable magic (got lost and gave up).
I haven't thought it through completely, but am quite sure I can solve
the problem if I use something other then
virtual functions. I could use functionoids (hope I got the right word
here) or could emulate the virtual fct mechanism completely under my
control. The first alternative is not as elegant as using virt
functions (and lacks from data members being inaccessible inside
functionoids), while the second is downright ugly.
Thanx,
Adrian
 
G

Gianni Mariani

macracan wrote:
....
Is there any way I can write it?


How about this:

// override check helper class
struct OverriddenCheck
{
friend class WindowSink;
friend void Subscribe(WindowSink &sink);

bool m_checking;

OverriddenCheck() : m_checking() {}

private:
enum OverrideState { Overridden, Default };

public:
void IsOverridden()
{
if ( m_checking ) throw Overridden;
}

private:
void IsDefault()
{
if ( m_checking ) throw Default;
}

}

struct WindowSink
{
OverriddenCheck m_check;

// ...
// default empty handlers
virtual void Move(int x, int y)
{
IsDefault();
}
virtual void Draw()
{
IsDefault();
}

private:
void IsDefault() // can only be called by methods in WindowSink
{
m_check.IsDefault();
}
};
//...
struct MyWindowSink : public WindowSink
{
// overwrite Draw only
void Draw()
{
m_check.IsOverridden();
}
};


void Subscribe(WindowSink &sink)
{
static WindowSink sinkref; // some reference to compare with
long mask = 0;

sink.m_check.m_checking = true;

try {
sink.Move(0,0);
// improperly implemented sink
abort();
} catch ( OverriddenCheck::OverrideState l_override )
if ( l_override == Overridden ) mask |= 1;
}

try {
sink.Draw();
// improperly implemented sink
abort();
} catch ( OverriddenCheck::OverrideState l_override )
if ( l_override == Overridden ) mask |= 2;
}

// there is probably some kind of template you can use to
// eliminate most of the try-catch blocks and write somthing like:

CheckOverride( sink, &WindowSink::Draw, mask, 1 );
CheckOverride( sink, &WindowSink::Move, mask, 2 );


sink.m_check.m_checking = false;

// subscribe to messages based on mask
XSelectInput(/* some other params */, mask);
}
int main()
{
MyWindodwSink sink;
//...
Enable(sink);
// ...
return 0;
}
 
M

macracan

....

The idea has merit, in the sense that calling a virtual function seems
to be just about the only reliable way to figure out where it lands
you. While I have no problem calling in members in WindowSink, I think
it would be weird to mandate a call through methods of MyWindowSink.
Not that it would force a certain syntax, because that can be
eliminated. I'm more worried about side-effects that 'faking' a
message from XWindows would have.
A fix would be to instead implement the handler in the virtual
function, rather link the virtual fct in MyWindowSink with the actual
handler via a puch-through mechanism: the first call establishes the
route followed in subsequent calls. And yet it seems strained...

More mulling required...

A

PS. this issue kinda reminds me of quantum mechanics. You don't know
the state of a qbit (value of a virtual pointer) until you measure it
(invoke it), but by that time you've altered the state (triggered
possible side-effects). How do you then figure out where a virtual
pointer points without calling it??? Hmmm... C++ has quantum
uncertainty...
 
A

Alf P. Steinbach

* macracan:
It has been discussed before, but I still can't find a solution and I
have a need. So here goes:

The problem:
I'm writing a something to handle messages from XWindows. The idea is
to have virtual handlers for different
kind of messages. But XWindows has a feature thereby you have to
subscribe to messages you're interested in.
I was thinking of providing empty handlers by default, and overwrite
them in derived classes. And I would need
to automatically detect which virtual fcts are overwritten, so I can
tell XWindows to which message I wish to subscribe.
Somewhat like so:
struct WindowSink
{
// ...
// default empty handlers
virtual void Move(int x, int y){}
virtual void Draw(){}
};
//...
struct MyWindowSink : public WindowSink
{
// overwrite Draw only
void Draw(){ /*some different behavior*/}
};
void Subscribe(WindowSink &sink)
{
static WindowSink sinkref; // some reference to compare with
long mask = 0;
// figure out which messages to subscribe to
if (&sinkref.Move != &sink.Move) mask |= 1;
if (&sinkref.Draw != &sink.Draw) mask |= 2;

// subscribe to messages based on mask
XSelectInput(/* some other params */, mask);
}
int main()
{
MyWindodwSink sink;
//...
Enable(sink);
// ...
return 0;
}

Now as the group already knows, the lines
if (&sinkref.Move != &sink.Move) mask |= 1;
if (&sinkref.Draw != &sink.Draw) mask |= 2;
are not valid C++ code anymore.
Is there any way I can write it?

BTW, I've looked into rtti (didn't find solution), and low level non-
portable magic (got lost and gave up).
I haven't thought it through completely, but am quite sure I can solve
the problem if I use something other then
virtual functions. I could use functionoids (hope I got the right word
here) or could emulate the virtual fct mechanism completely under my
control. The first alternative is not as elegant as using virt
functions (and lacks from data members being inaccessible inside
functionoids), while the second is downright ugly.

In order to land on a good solution you have to consider also dispatch
to the event handler functions, and extensibility, i.e. adding new ones.

And that general problem is quite complex.

I remember having a long discussion with Andrei Alexandrescu over in
comp.lang.c++.moderated about this. Andrei maintained that this problem
showed the need for language support for post-constructors in C++, I
maintained that it did not, but then, the concrete problem wasn't
explained until well into the debate where I'd already made my stand.
Anyways, the solution sketch below uses the idea of post-construction:

<code>
#include <cstddef>
#include <map>
#include <memory>

#include <iostream>
#include <ostream>

void say( char const s[] ) { std::cout << s << std::endl; }

namespace windowEvent
{
struct Data { long id; Data( long x ): id( x ) {} };

class Dispatcher
{
public:
virtual void dispatch( Data const& ) = 0;
};

class Handler;
};

class WithFinalInit
{
template< typename T> friend
std::auto_ptr<T> fullyInitialized( std::auto_ptr<T> );

public:
struct Obscurity {};

static void* operator new( std::size_t size, Obscurity const& )
{
return ::eek:perator new( size );
}

static void operator delete( void* p, Obscurity const& )
{
::eek:perator delete( p );
}

virtual ~WithFinalInit() {}

private:
virtual void doFinalInit() = 0;
};

template< typename T >
std::auto_ptr<T> fullyInitialized( std::auto_ptr<T> p )
{
static_cast<WithFinalInit*>( p.get() )->doFinalInit();
return p;
}

#define NEW_WINDOW( type, args ) \
fullyInitialized( std::auto_ptr<type>( \
new((WithFinalInit::Obscurity())) type args ) \
)

class WindowWithEvents
: public WithFinalInit
, protected windowEvent::Dispatcher
{
friend class windowEvent::Handler;
friend class Window;

private:
typedef std::map<long, windowEvent::Dispatcher*> EventMap;
EventMap myEvents;

void addEventHandler( long id, windowEvent::Dispatcher& handler )
{
say( "Adding event handler" );
myEvents[id] = &handler;
}

virtual void dispatch( windowEvent::Data const& eventData )
{
EventMap::const_iterator const it = myEvents.find( eventData.id );
if( it != myEvents.end() )
{
windowEvent::Dispatcher* const handler = it->second;
handler->dispatch( eventData );
}
}

virtual void doFinalInit()
{
long mask = 0;
for(
EventMap::const_iterator it = myEvents.begin();
it != myEvents.end();
++it
)
{
mask |= it->first;
}
say( "XSelect()" );
//XSelectInput(/* some other params */, mask);
}

WindowWithEvents()
{ say( "WindowWithEvents::<init>() finished" ); }

public:
virtual ~WindowWithEvents() {}
};

class Window: public WindowWithEvents
{
// Note: this class is necessary even without any member functions.
public:
void testDispatch( long id ) { dispatch( id ); }
};

namespace windowEvent
{
class Handler: public Dispatcher
{
protected:
Handler( WindowWithEvents& w, long id )
{
w.addEventHandler( id, *this );
say( "Handler::<init>() finished" );
}
};

class Move: public Handler
{
protected:
virtual void dispatch( Data const& eventData )
{
onMove( 123, 456 );
}

public:
Move( WindowWithEvents* w ): Handler( *w, 1 )
{ say( "Move::<init>() finished" ); }

virtual void onMove( int x, int y ) = 0;
};

class Draw: public Handler
{
protected:
virtual void dispatch( Data const& eventData )
{
onDraw();
}

public:
Draw( WindowWithEvents* w ): Handler( *w, 2 )
{ say( "Draw::<init>() finished" ); }

virtual void onDraw() = 0;
};
} // namespace windowEvent


//------------------------ Client code:

struct MyWindow
: Window
, windowEvent::Move
, windowEvent::Draw
{
protected:
virtual void onMove( int x, int y ) { say( "Moving" ); }
virtual void onDraw() { say( "Drawing" ); }

public:
MyWindow()
: windowEvent::Move( this )
, windowEvent::Draw( this )
{ say( "MyWindow::<init>() finished" ); }

~MyWindow() { say( "MyWindow::<destroy>()" ); }
};

int main()
{
std::auto_ptr<MyWindow> w = NEW_WINDOW( MyWindow,() );
w->testDispatch( 1 );
w->testDispatch( 2 );
}
</code>

<output>
WindowWithEvents::<init>() finished
Adding event handler
Handler::<init>() finished
Move::<init>() finished
Adding event handler
Handler::<init>() finished
Draw::<init>() finished
MyWindow::<init>() finished
XSelect()
Moving
Drawing
MyWindow::<destroy>()
</output>

It's an interesting question whether this program exhibits formally
Undefined Behavior.

Disclaimer: only tested with one (old) compiler.

Cheers, and hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top