Thursday, 15 January 2015

c++ - How to write a template resulting in a primitive type? -


I am writing a small fixed point arithmetic class with the template parameter for integer and partial bits. When two small fixed point types multiply, capturing the full result result is considered a big fixed point type. like . A 16.16 fixed point number multiplied by two 8.8 fixed point number result

My class looks like this:

  of the template & lt; Typename t, unsigned int bits, unsigned int frac & gt; FixedPoint {Public: constexpr FixedPoint (int x = 0): raw_ (x & lt; & lt; frac) {} FixedPoint (double x) constexpr: raw_ (x * (t (1) & lt; ; Frac)} {} Private: T raw_; }  

The problem now is the T template parameter, especially for the multiplication, the result types are different from the logic types and can not be sent to them. writing a * b does not work

T template type what I want to do to replace the int & lt ;. Bits + frac & gt; that depends on the number of int8_t, int16_t, int32_t or int64_t bits is required for the total

can I write such a type? I'm actually ok with this limited to 8, 16, 32 or 64 bit.

"itemprop =" text ">

after simple

Code> template & lt; Std :: size_t bits & gt; Std :: int16_t, conditional_t ​​& lt; (Bits & lt; = 32), std :: int32_t, enable_if_t & lt; (Bits and lieutenant;) using integer_with_bits = conditional_t ​​& lt; (Bits & lt; = 8), std :: int8_t, conditional_t ​​& lt; (Bits & lt; = 16); = 64), std :: int64_t> & Gt; & Gt; & Gt ;;

Which is the compile-time equivalent to run-time ?:?:?:?: Cascade then integer_with_bits & lt; 3 & gt; is int8_t , while integer_with_bits & lt; 65 & gt; (and larger) a compile time generates errors. In the above, I used the oxylleries

  template & lt; Bool c, typename T & gt; Enable_if_t = typename std :: enable_if & lt; C, T & gt; :: type; Template & lt; Bool c, typename t1, typewriter t2 & gt; Conditional_t ​​= typename std :: conditional & lt; C, T1, T2 & gt; :: type;  

No comments:

Post a Comment