Pages

2011-02-21

C++: Prevent the compiler from doing implicit type conversion

Use the keyword explicit on the constructor. Forcing explicit conversions is usefull
to make the programmers aware of the conversion. This is especially interesting for
time consuming conversions.
struct A
{
A() {}
};

struct B
{
B() {}
B(const A &a) {}
};

struct C
{
C() {}
explicit C(const A &a) {}
};

void fb(B b) { /* ... */ }

void fc(C c) { /* ... */ }

void function()
{
A a;
B b;
C c;
fb(a); // ok, conversion is implicit
fc(a); // error
fc(C(a)); // ok, conversion is explicit
}

2011-02-07

C++ MFC: Catching Windows Events

  •     LRESULT DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
    {
        switch(message)
        {
            case WM_COPY:
            case WM_PASTE:
                break;
            default:
                return
__super::DefWindowProc(message, wParam, lParam);
                break;
        }
        return 0;
    }

  •     LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
    {
        switch(message)
        {
            case WM_COPY:
            case WM_PASTE:
                break;
            default:
                return
__super::WindowProc(message, wParam, lParam);
                break;
        }
        return 0;
    }

  •     BOOL PreTranslateMessage(MSG* pMsg)
    {
        if (pMsg->message==258 && LOWORD(pMsg->wParam)==22)
        //if (pMsg->message == WM_COPY || pMsg->message == WM_PASTE)
        {
            // handle the paste however you want to here
            pMsg->wParam=0;
            pMsg->message=0;
            return TRUE;
        }
        return
__super::PreTranslateMessage(pMsg);
    }

  •     BOOL OnCommand(WPARAM wParam, LPARAM lParam)
    {
        switch (LOWORD(wParam))
        {
            case WM_CUT:
            case WM_COPY:
            case WM_PASTE:
                return TRUE;
                break;
            default:
                return __super::OnCommand(wParam, lParam);
                break;
        }   
    }