我如何检查给定的 int(或任何其他数据类型)是有符号的还是无符号的? 搜索的时候发现了这个功能,
std::numeric_limits<int>::is_signed
但是我只能输入数据类型,有没有办法可以通过变量名来检查,比如。
signed int x = 5;
现在我想创建一个函数来检查 x 是否为有符号整数。
如果你们能回答这些小问题,我们将不胜感激。
- 为什么我们在 std 之后使用 '::' 这些运算符?
- 我们在std::cout中使用它们是什么意思,是一样的吗?
- 这里的 numeric_limits<> 是一个类还是什么?
- 再一次,为什么我们要在 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/