concurrencyboy
concurrencyboy

Reputation: 371

check if the variable is signed using is_signed

I want to check if the variable is signed. I've found a class template whose name is is_signed but I cannot use it since I'm new for C++. How can I check that the variable is signed?

#include <iostream>
#include <cmath>

int main() {
    // the following short initialization is on purpose
    short price {10u};
    std::cout << std::is_signed<price>::value << '\n';
    return 0;
}

Upvotes: 1

Views: 1438

Answers (3)

Stack Danny
Stack Danny

Reputation: 8126

is_signed - like many other of these structs is a way to perform a check on a type - but not on a variable. you can use decltype to get the underlying type of your variables.

std::cout << std::is_signed<decltype(price)>::value << '\n'; //-> 1

Also - is_signed is defined in <type_traits> and not <cmath>.


as already mentioned in the comments; if your intention is to simply see if the variable is positive or negative you won't need any library utilities.

To get that information use price > 0 or price < 0 respectively. These are, of course, runtime only operations.

Upvotes: 7

Li Chen
Li Chen

Reputation: 5270

the implementation of is_signed can be something like

template<bool IsArithmetic, typename T> struct is_signed_impl : bool_constant<T(-1) < T(0)>
    {};

template<typename T> struct is_signed_impl<false, T> : false_type
    {};

template<typename T> struct is_signed
        : is_signed_impl<is_arithmetic_v<T>, T>
    {};

the template variable T in is_signed<T> is finally used in T(-1) < T(0), which is for casting. If T is a non-type argument likeprice, the cast is not well-formed.

Upvotes: 0

Nuclear
Nuclear

Reputation: 1458

Arguments to Class Templates must be types. If you have a variable and you wan to get it's type, you can use decltype:

std::cout << std::is_signed<decltype (price)>::value << '\n';

Upvotes: 1

Related Questions