c++ - 是 unsigned char ('0' ) 合法的 C++

标签 c++

以下代码在 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/

相关文章:

c++ - 将 Box2D 与 SDL 中的现有游戏类结构集成?

c++ - opengl - 镜像着色器的可能性?

c++ - 如何使用数组将多个字符串文字传递给函数(无 vector )

scikit-learn 中 kmeans 的 python 内存错误

c++ - 有没有一种简单的方法可以让 `boost::ptr_vector` 在 Visual Studio 中对调试器更加友好?

c++ - 跟踪动态内存

c++ - C/C++、Windows 控制台应用程序的速度是否取决于目标是 32 位还是 64 位?

c++ - 带有列表初始化的模棱两可的构造函数调用

c++ - 非重复随机数发生器

c++ - 我的辅音/元音替换器有什么错误?