C++ says that one of the function of reinterpret_cast is
A pointer to an object can be explicitly converted toand
a pointer to an object of different type.
Plain char, signed char, and unsigned char are three distinct types.in ISO/IEC14882:2003.
Hence, as the type of string literal is const char*, following code can not be compiled in C++.
unsigned char* message = "Hello, the World.";In this case, the code requires reinterpret_cast<unsigned char*>(foo) or static_cast<unsigned char*>(static_cast<void*>(foo)) to convert from unsigned char* to char*. In addition, the code requires const_cast because standard conversion from const char* to char* does not apply with this case from const unsigned char* to unsigned char*.
Such casts are so dirty.
Some compilers such as VC7.1 have the option which makes literals to unsigned. But that is not standard C++ but implementation-extension.C++ also says
A char, a signed char, and an unsigned char occupy the sameSo the conversion between unsigned char* and char* are normally safe. Hence, I think that double static_cast are well-formed. But, I wraps the casts as string_cast, because the double static_cast are too long.
amount of storage and have the same alignment requirements.
string_cast sample excepted const_cast is following
template<typename OUT> OUT* string_cast(unsigned char* str);
template<typename OUT> OUT* string_cast(char* str);
template<> inline unsigned char* string_cast(char* str)
{ return static_cast<unsigned char*>(static_cast<void*>(str)); }
template<> inline char* string_cast(unsigned char* str)
{ return static_cast<char*>(static_cast<void*>(str)); }For example, char* str and unsigned char* ustr are defined previously,str = string_cast<char>(ustr);
or ustr = string_cast<unsinged char>(str); are fine.
No comments:
Post a Comment