Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unsigned char('0') legal C++

Tags:

c++

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++?

like image 439
qaz Avatar asked Jul 08 '10 23:07

qaz


2 Answers

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.

like image 87
GManNickG Avatar answered Sep 29 '22 17:09

GManNickG


The prefered method of casting in C++ is to use static_cast like so:

int a = static_cast<unsigned char>( '0' );
like image 24
wheaties Avatar answered Sep 29 '22 17:09

wheaties