bits and bytes

Jesus Loves You. C, C++, VC++, .net code snippets and articles, based on Nibu’s day to day programming experiences.

Dynamically determining the base class of a class using templates

Posted by Nibu Thomas on November 27, 2007

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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>