简体   繁体   中英

signed or unsigned int in c++

How can i check if given int(or any other data type) is signed or unsigned? I found this function while searching,

std::numeric_limits<int>::is_signed

But i can only input the data type, is there a way that i can check by variable name, like.

signed int x = 5;

Now i want to make a function which checks that x is a signed int or not.

And if you guys can answer these little questions, that would be highly appreciated.

  1. Why do we use '::' these operators after std?
  2. What do they mean when we use them in std::cout, is it the same?
  3. Here numeric_limits<> is a class or what?
  4. And again, why are we using these '::' before is_signed?

is there a way that i can check by variable name

Since C++11, we have decltype to get the type of a variable or expression:

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

Historically, it was trickier; the only way to infer a type from a variable was through template argument deduction:

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

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

That's the scope resolution operator, saying that we want the name numeric_limits to be looked up in the namespace std .

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

Yes. Like most names in the standard library, cout is also scoped inside namespace std .

Here numeric_limits<> is a class or what?

It's a class template, containing various static variables and functions that describe the type used as the template argument. Here's a reference: http://en.cppreference.com/w/cpp/types/numeric_limits

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

Again, that resolves the scope by saying we want the name is_signed to be looked up inside the class scope of std::numeric_limits<int> .

Like this:

constexpr bool is_signed = std::numeric_limits<decltype(x)>::is_signed();

This will fail to compile if there's no specialization of numeric_limits for the type of x , though. A more generic solution would be is_signed from <type_traits> header:

constexpr bool is_signed = std::is_signed<decltype(x)>::value;

And yes, both are numeric_limits and is_signed are class templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM