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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With