The following compiles in Visual Studio but fails to compile under g++.
int main()
{
int a = unsigned char('0');
return 0;
}
Is unsigned char() a valid way to cast in C++?
No, it's not legal.
A function-style explicit type conversion requires a simple-type-specifier, followed by a parenthesized expression-list. (§5.2.3) unsigned char
is not a simple-type-specifier; this is related to a question brought up by James.
Obviously, if unsigned char
was a simple-type-specifier, it would be legal. A work-around is to use std::identity
:
template <typename T>
struct identity
{
typedef T type;
};
And then:
int a = std::identity<unsigned char>::type('0');
std::identity<unsigned char>::type
is a simple-type-specifier, and its type is simply the type of the template parameter.
Of course, you get a two-for-one with static_cast
. This is the preferred casting method anyway.
The prefered method of casting in C++ is to use static_cast
like so:
int a = static_cast<unsigned char>( '0' );
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