Advertisement

Question about win32 window templates

Started by November 26, 2014 01:58 PM
1 comment, last by SteveHatcher 10 years, 1 month ago

I have been working through Microsoft's "Learn to Program for Windows in C++" articles found here

Learn to Program for Windows in C++

http://msdn.microsoft.com/en-us/library/windows/desktop/ff381399%28v=vs.85%29.aspx

and have a question about the end of module 1: http://msdn.microsoft.com/en-us/library/windows/desktop/ff381400%28v=vs.85%29.aspx

In their sample they derive a window from a base class, where the base class is as follows:


template <class DERIVED_TYPE>
class BaseWindow
{
public:
    static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
    {
        DERIVED_TYPE *pThis = NULL;
...etc

I am just trying to understand why this is created as a template. My understanding of class templates is to allow us to write a class, and use that class for any data type we want. Eg MyVector<int> or MyVector<double>

In this case I cant understand why they have used a template class. Can they just have gone


class MainWindow : public BaseWindow

Instead they have used


class MainWindow : public BaseWindow<MainWindow>

I just cant understand what other kinds of windows can be "derived" from this base case? I can understand in the case of calling a function with an int or a float, and needing a template there, but not in this case.

Thanks for your time

This is what is commonly known as the Curiously Recurring Template Pattern.

Basically, the base class needs to know the derived class' type for some reason.

In this particular case it is used to dispatch the windows messages to your class. They store your this pointer into the special window storage location on window creation, and then retrieve it when a message comes into the static window message handler so they can call the virtual message handler on it.

Granted, I am not entirely sure why they did it this way. BaseWindow has the virtual message handler function, so they could have just stored the BaseWindow this pointer and dispatched that way.
Advertisement

Thanks for the answer SmkViper. I still cant quite understand the purpose of these CRTP's, doing some reading now to figure it out.

This topic is closed to new replies.

Advertisement