开发者

How do I determine the number of bits in a template non-type integral constant parameter?

I would assume that this is covered in the C++ Standard, but I've not been able to find it. I am writing some templates that are going to do arithmetic on their non-type int开发者_StackOverflow中文版egral parameters, and I find I need the equivalent of MAX_INT for the parameter 'x' in a template like template <int x> Foo.

Ideally someone could point me to the paragraph in the standard (if one exists) that gives the allowable ranges for the sizes of integral template parameters and any way of determining the actual number of bits on a particular implementation.

--

To clarify: its the templates that will be doing the math within the type system, as part of a metaprogramming library. The 'int' will never be instantiated, and will never take up runtime storage. In many ways its analogous to the math done by the preprocessor, and in that case I know that the integral types are not guaranteed to be the same size as an 'int'. What I am looking for is the part of the standard that says if the types ARE the same or not, and if not, how many bits are used by template integral parameters during compilation.


See numeric limits. The documentation for std::numeric_limits<>::digits says:

For integer types: number of non-sign bits (radix base digits) in the representation. For floating types: number of digits (in radix base) in the mantissa (equivalent to FLT_MANT_DIG, DBL_MANT_DIG or LDBL_MANT_DIG).

Edit:

There are other methods, such as min(), max() and the like.


You need the numeric_limit class http://www.cplusplus.com/reference/std/limits/numeric_limits/

Specifically,

numeric_limits<T>::max()

will give you CHAR_MAX, SCHAR_MAX, UCHAR_MAX, SHRT_MAX, USHRT_MAX, INT_MAX, UINT_MAX, LONG_MAX, ULONG_MAX, FLT_MAX, DBL_MAX or LDBL_MAX, depending on T.


See here: http://www.boost.org/doc/libs/1_41_0/libs/integer/integer_traits.html

Edit: Actually it's not giving you any information about the standard however you can get the min and max value on compile time for certain types.

Edit2: According to your update I can suggest you to use boost.mpl, boost.type_traitsand the before mentioned boost.integer_traits library.

Boost also provides a header called cstdint.hpp (part of the boost.integer library) which defines types like boost::uint32_t or boost::int32_t which will ensure that you get a type which supports 32 Bits. (Of course also for 8, 16 and 64 Bits)

With boost.type_traits you can for example compare two types if they are equal. You'd be using boost::is_same for it.

Boost MPL offers you compile time algorithms, to make conditions etc and integer traits will offer you a compile time way to get the limits for types.

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜