Tuesday 15 July 2014

c++ - Function checking if an integer type can fit a value of possibly different (integer) type -


Is it possible to create a templated function that checks that a primitive data type might possibly fit the values ​​of different primitive data types Can do? Let's limit the scope to the integer type for the moment.

More precise: Is compiler warnings (Although Boolean expression is not always true / false, signed / unsigned, it is now possible to create "All Fit" templated tasks, comparisons, unused variables) and compiler warning Without disabling the investigation? The function should be limited to check as much as possible on the runtime (all trivial cases should be excluded at compile time). If possible, I would like to avoid and prefer to use the extension from C ++ 11 (unless "Old" is not a "quick" replacement for C ++).

Note: "Price" is not known at the time of compilation, only its type.

Examples of expected behavior:

  int main (int argc, char ** argv) {for (int i = 1; i & lt; argc; i ++ ) {Cans int value = Atoy (AGR [i]); Std :: cout & lt; & Lt; Price & lt; & Lt; ":"; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Int8_t & gt; (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Uint8_t & gt; (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Int16_t & gt; (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Uint16_t> (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Int32_t & gt; (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Uint32_t> (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Int64_t & gt; (Value) & lt; & Lt; ""; Std :: cout & lt; & Lt; CanTypeFitValue & lt; Uint64_t> (Value) & lt; & Lt; Std :: endl; }} ./a.out 6 1203032847 2394857 -13423 9324-192992929 6: 1 1 1 1 1 1 1203032847: 0 0 1 1 1 1 23 9 497 7: 0 0 1 1 1 1 -13423: 0 0 1 0 1 0 1 0 9 324: 0 0 1 1 1 1 1 1 -1929 9 29 9 0 0 0 0 1 0 1 0   

Check your code or .

Check the assembly created.

This question was inspired by

numeric_limit and using types Stdint.h Defined in

more compact that is mine, same capacity.

DRAWack: To include an additional header.

  #include & lt; Border & gt; # Include & lt; Stdint.h & gt; Using Std :: numeric_limits; Template & lt; Typename t, typename u & gt; Bull Can notify Value (Cost U Value) {CONSTEMEMX_T BOTTi = Intmax_T (Numeric_Limits  :: MIN ()); Const intmax_t botU = intmax_t (numeric_limits & lt; U & gt;: min ()); Const uintmax_t topT = uintmax_t (numeric_limits & lt; T & gt; :: max ()); Const uintmax_t topU = uintmax_t (numeric_limits & lt; U & gt; :: max ()); Return (Botty> BOTU & amp; Price & amp; Lt; Static_Cast & lt; U & gt; (Boat)) || (Top & Left; TopU & amp; Price & gt; Static_Cast & lt; U & gt; (Top T)); }   

(You can change T and U type)


Note: One was written, but apparently there are some problems Are there and

No comments:

Post a Comment