以下代码在 Visual Studio 中编译但在 g++ 下编译失败。
int main()
{
int a = unsigned char('0');
return 0;
}
unsigned char() 是一种有效的 C++ 转换方式吗?
最佳答案
不,这是不合法的。
函数式显式类型转换需要一个简单类型说明符,后跟一个带括号的表达式列表。 (§5.2.3) unsigned char
不是简单类型说明符;这与 James 提出的问题有关.
显然,如果 unsigned char
是一个简单类型说明符,它将是合法的。解决方法是使用 std::identity
:
template <typename T>
struct identity
{
typedef T type;
};
然后:
int a = std::identity<unsigned char>::type('0');
std::identity<unsigned char>::type
是一个简单类型说明符,它的类型只是模板参数的类型。
当然,您可以通过 static_cast
获得二合一的优惠.无论如何,这是首选的类型转换方法。
关于c++ - 是 unsigned char ('0' ) 合法的 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3208657/