I have this class which I want to pass around Windows as LPARAM parameter. Since it's small enough to fit inside LPARAM I want to pass it by value, but in case it expands later I want it to automatically switch to passing by reference.
I would use something like
typedef boost::call_traits<CMyClass>::param_type CMyClassParam;
which should be either const CMyClass
or const CMyClass&
depending on whether sizeof(CMyClass) <= sizeof(LPARAM)
but call_traits optimizes only small PODs, not small classes.
typedef is taken care of by advice of Anycorn:
typedef boost::mpl::if_c<(sizeof(CMyClass) <= sizeof(LPARAM)), CMyClass, CMyClass&>::type CMyClassParam;
And then, how do I convert between CMyClassParam and LPARAM (in case you don't know, LPARAM is int, long enough to store a pointer)
CMyClass::operator LPARAM()
{
// must be either
return *(LPARAM*)this;
//or
return reinterpret_cast<LPARAM>(this);
}
//so that I may call:
void SomeWinFunc(LPARAM p);
CMyClass vi;
SomeWinFunc(vi);
// and then get it back:
void SomeWinCallback(LPARAM p)
{
CMyClassParam vi = (?????)p;
// which should translate into either
CMyClass ti = *(CMyClass*)(&p); // make a bitwise copy
// or
CMyClass& ti = *(CMYClass*)p;
}
struct
into anint
because the machine may have integral throwing NaNs that cause an exception just by copying the value. More practically, this will probably work but violates strict aliasing rules as written… unfortunately I don't know if I can help with those rules…