integer traits (is_integer, is_integral)
I need two traits concerning integers.
The first one would be like
std::is_integral
(orboost::is_integral
), but usable with user defined types (for example a class wrapping anint
, sayint_wrapper
): true if the type be开发者_StackOverflow中文版haves like an integer and whose representation is like standard integral types (e.g.sizeof(T) * CHAR_BITS == std::numeric_limits<T>::digits
ifT
is unsigned) But the definition of an integral type is very rigid, in that it consists of a list of these types. So specializingstd::is_integral
seems difficult, if not forbidden (though not stated explicitly I think):is_integral
is a "primary" type trait (20.7.4.1, note 3: exactly one primary type trait is true for a type T, in my caseint_wrapper
has alreadyis_class
equal to true). What are the risks I take if I specialize this trait forint_wrapper
? Do you know of a trait class (e.g. in Boost) that fit my needs?The second trait I need is for types having integer semantics (with bits arithmetic operations, bit manipulations etc.). For example the
mpz_class
from GMP would satisfy this trait. Isstd::numeric_limits<T>::is_integer
appropriate for this trait? I read both that it is OK to specialize and setnumeric_limits<T>::is_integer == true
ifT
behaves like an integer, but also (in the C++ standard) that the terms "integral" and "integer" are synonymous (in which case we sould always havenumeric_limits<T>::is_integer == is_integral<T>::value
)
In conclusion, am I better of defining my own traits for my precise needs, or try extending standard ones?
It depends whether you want boost and other standard libraries to treat your class as integral. If so, you have no other way but specialize std/boost::is_integral<>. Otherwise make your own is_integral<> with its default implementation forwarding to std/boost::is_integral<> and specialize it for your integral wrapper.
精彩评论