|
-
October 4th, 2002, 06:43 AM
#1
Casting angst (makes me feel like a newbie)
Hello guys,
Can anyone tell me a safe, nice way to cast between an integral type and a pointer to an object? And vice-versa? I want to use std C++.
eg class CMyThing { ..... };
int main()
{
CMyThing *pObj;
float f;
pObj = some_cast<????>( f );
}
Please dont comment on the why's of this type of operation. I HAVE to do it to work with my current projects legacy code. Its not my fault,honest But I would like to rewrite the old casts that were there to use the correct relevant casts. I had understood reinterpret_cast<> to allow casting arbitrarily, but three compilers I have tried refused to cast a float to a class pointer.
Thanks for all help.
- solosnake
Last edited by solosnake; October 4th, 2002 at 06:47 AM.
-
October 4th, 2002, 07:45 AM
#2
Casting between pointers and integer types does work with reinterpret_cast. Your problem is that a float is not an integer type.
So the following does work:
Code:
int value = 5;
CMyThing *pObj = reinterpret_cast<CMyThing *>( value );
In order to stuff a float value into a pointer, one way is to cast the lvalue so that you can assign a float on top of the pointer.
(Don't ever use this pointer as a pointer).
Code:
float f = 10.0;
* reinterpret_cast<float *>( &pObj ) = f;
What this code is doing is treating the address of pObj as a pointer to a float, and the dereferencing it so that the float can be assigned.
Best regards,
John
-
October 4th, 2002, 07:52 AM
#3
Float is not an integral type. I would have thought that (unsigned) int or long would be better suited, depending on which one (if either) is the same size as your pointer.
Alternatively, find the author of the troublesome code and point out the error of their ways to them.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
October 4th, 2002, 08:06 AM
#4
Thanks for the casting help.
Also I used integral to mean 'native', which to me includes 'floats' etc, however you are correct, in C++ parlance this does mean only the integer types.
Thanks for the help!
- solosnake
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|