2

I have as class as follows:

#include <Windows.h>
class MyClass
{
   void A();
   static BOOL CALLBACK proc(HWND hwnd, LPARAM lParam);
};

void MyClass::A()
{
   EnumChildWindows(GetDesktopWindow(), MyClass::proc, static_cast<LPARAM>(this));
}

BOOL CALLBACK MyClass::proc(HWND hwnd, LPARAM lParam)
{
   // ...
   return TRUE;
}

When I attempt to compile this in Visual C++ 2010, I get the following compiler error:

error C2440: 'static_cast' : cannot convert from 'MyClass *const ' to 'LPARAM' There is no context in which this conversion is possible

If I change the definition of MyClass::A as follows, then the compile succeeds:

void MyClass::A()
{
   EnumChildWindows(GetDesktopWindow(), MyClass::proc, (LPARAM)this);
}

What is the explanation for the error in the first example?

JBentley
  • 6,099
  • 5
  • 37
  • 72

3 Answers3

8

You need to use a reinterpret_cast not a static_cast to perform a cast to a completely unrelated type. See this When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? for more details on the different types of C++ casts.

Community
  • 1
  • 1
shf301
  • 31,086
  • 2
  • 52
  • 86
4

static_cast is used to cast related types, such as int to float, and double to float, or conversions which need too little effort, such as invoking single-parameter constructor, or invoking a user-defined conversion function.

LPARAM and this are pretty much unrelated, so what you need is reinterpret_cast:

LPARAM lparam =  reinterpret_cast<LPARAM>(this);
EnumChildWindows(GetDesktopWindow(), MyClass::proc, lparam);
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

As you know, the this pointer is const and the static_cast operator cannot cast away the const, volatile, or __unaligned attributes. Take a look at this link on MSDN.

TonySalimi
  • 8,257
  • 4
  • 33
  • 62