Home > C++, VC++ > Dynamically determining the base class of a class using templates

Dynamically determining the base class of a class using templates

Well nearly dynamically! When working on the ATL COM framework I came across a piece of framework code which makes a template parameter as the base class of a class which looked quite useful to me.

Here is a demo…

template<class BaseClass = CWnd> class SomeWnd : public BaseClass
{
    public:
      LRESULT WindowProc(UINT uMessage, WPARAM wParam, LPARAM lParam );
};    

template</class><class BaseClass>
LRESULT SomeWnd<baseclass>::WindowProc( UINT uMessage, WPARAM wParam, LPARAM lParam )
{
    //... Do some additional processing here ...
    return BaseClass::WindowProc( uMessage, wParam, lParam );
}   

class MyDialog : public SomeWnd<cdialog>
{
};     

class MyFrame : public SomeWnd<cframewnd>
{
};   

class MyCustomWindow : public SomeWnd<> // Use default template param
{
};

Now you may ask why I needed this, well I had to write some code in the WindowProc of a window class, but the base differed from implementation to implementation, so I adapted this idea from the ATL COM framework.

Since WindowProc is found in all CWnd derived window classes and at the same time I also needed to call the correct the default base implementation too, so this helped.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: