c++ - C++ 中的有符号或无符号整数

标签 c++ std unsigned signed

我如何检查给定的 int(或任何其他数据类型)是有符号的还是无符号的? 搜索的时候发现了这个功能,

std::numeric_limits<int>::is_signed

但是我只能输入数据类型,有没有办法可以通过变量名来检查,比如。

signed int x = 5;

现在我想创建一个函数来检查 x 是否为有符号整数。

如果你们能回答这些小问题,我们将不胜感激。

  1. 为什么我们在 std 之后使用 '::' 这些运算符?
  2. 我们在std::cout中使用它们是什么意思,是一样的吗?
  3. 这里的 numeric_limits<> 是一个类还是什么?
  4. 再一次,为什么我们要在 is_signed 之前使用这些“::”?

最佳答案

is there a way that i can check by variable name

从 C++11 开始,我们有 decltype获取变量或表达式的类型:

std::numeric_limits<decltype(x)>::is_signed

从历史上看,它更棘手;从变量推断类型的唯一方法是通过模板参数推导:

template <typename T>
bool is_signed(T const &) {
    return std::numeric_limits<T>::is_signed;
}

Why do we use '::' these operators after std?

那是作用域解析运算符,表示我们想要名称 numeric_limits在命名空间 std 中查找.

What do they mean when we use them in std::cout, is it the same?

是的。与标准库中的大多数名称一样,cout也在 namespace std 内.

Here numeric_limits<> is a class or what?

它是一个类模板,包含各种描述用作模板参数的类型的静态变量和函数。这是一个引用:http://en.cppreference.com/w/cpp/types/numeric_limits

And again, why are we using these '::' before is_signed?

同样,通过说我们想要名称 is_signed 来解析范围在 std::numeric_limits<int> 的类范围内查找.

关于c++ - C++ 中的有符号或无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825015/

相关文章:

c++ - C++ 中的 pthread_create 错误(类内的 pthread)

具有动态大小的 Python C 扩展类

c++ - std::sort 仿函数一行

c++ - 在分配之前 memset() 一个 std::iterator 变量是否安全?

Java:无符号数

c++ - 浮点乘法可以在 C++ 中抛出异常吗?

c++ - 将可变参数模板参数解包到初始化列表中

c++ - 标准排序似乎永远循环

从 unsigned long int 转换为 signed int,反之亦然

c - mspgcc 中的意外结果