Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template distinguish between signed and unsigned

If have written a template function and the code only work correct if the template type is unsinged. Now I search for a way to prevent the fumction from compiling with signed types, without C++11.

template<typename T>
T foo() {
    T a=0;
    return a<<1;
}
like image 902
gerum Avatar asked Feb 27 '26 16:02

gerum


2 Answers

std::is_signed is only available since C++11, however before you can use std::numeric_limits<T>::is_signed.

As static_assert is also C++11, you have to use something else, eg the trick from here:

typedef int static_assert_something[something ? 1 : -1];
like image 55
463035818_is_not_a_number Avatar answered Mar 02 '26 05:03

463035818_is_not_a_number


Without library: for signed types, ~T(0) < T(0) but for unsigned types, ~T(0) > T(0). These are compile-time constants. See the other answer how to turn that into an error.

like image 37
MSalters Avatar answered Mar 02 '26 06:03

MSalters