brekehan:
> I've always been a little sketchy on the differences between static,
> dynamic, and reinterpret casting. I am looking to clean up the
> following block by using C++ casting instead of the C style casting.
> from what I am reading, I should use reinterpret cast in this
> situation, is that correct? Why does static and dynamic casting fail
> me?
If you want to replace all "(Type)" casts with the "xxxx_cast" family, then
the following is a quick reliable method which doesn't require any
intelligence. (Before I begin, I'll assume that the code you're dealing
with has no need for dynamic_cast.)
Replace all casts with "static_cast", then re-compile. If you don't get any
errors, then you're good to go. If you _do_ get errors though, go through
the error lines and replace the offending static_cast's with const_cast.
Re-compile again. If you get errors for the const_cast's, then replace the
offending const_cast's with reinterpret_cast. If you still get errors for
the reinterpret_cast's, then you'll need a combination of reinterpret_cast
and const_cast.
The following is an example where a "(Type)" style cast would need to turn
into two casts:
int const arr[4] = {0,1,2,3};
char *p = (char*)arr;
would become:
char *p = reinterpret_cast<char*>( const_cast<int(&)[4]>(arr) );
or, the more convenient method which doesn't need to know the type of
"arr":
char *p = const_cast<char*>(
reinterpret_cast<char const volatile*>(arr) );
Lately, I've been intentionally paranoid about new features being added to
the language which could possibly break code like this, so I think it might
be wise to replace "char const volatile" with something like:
typedef char const volatile most_strict_char;
That way, if a new modifier like "cache" is added to the language, we just
need to add it to the typedef:
typedef char const volatile cache most_strict_char;
Then again, we could always make a function out of it, or even a macro:
#define MOST_STRICT_TYPE(type) type const volatile
--
Frederick Gotham
|