fork download
  1. #include <iostream>
  2. #include <inttypes.h>
  3. #include <type_traits>
  4.  
  5. template <int F>
  6. struct fp
  7. {
  8. constexpr static const unsigned int BITSF = F;
  9. int32_t s;
  10.  
  11. template<class B = int, typename std::enable_if<!std::is_same<B, int32_t>::value>::type...>
  12. fp(const int & b) : s(((int32_t)b) << F) { }
  13. fp(const int32_t & b) : s(b << F) { }
  14. fp(const float & b) : s(b * (1 << F)) { }
  15. template<int T>
  16. fp(const fp<T> & b) { *this = b; }
  17.  
  18. template<class B = int, typename std::enable_if<!std::is_same<B, int32_t>::value>::type...>
  19. fp & operator=(const int & b) { s = ((int32_t)b) << F; return *this; }
  20. fp & operator=(const int32_t & b) { s = b << F; return *this; }
  21. fp & operator=(const float & b) { s = b * (1 << F); return *this; }
  22. fp & operator=(const fp & b) { s = b.s; return *this; }
  23.  
  24. template<int T>
  25. fp & operator=(const fp<T> & b)
  26. {
  27. if (T > F) { s = b.s >> (T - F); }
  28. else if (T < F) { s = b.s << (F - T); }
  29. else { s = b.s; }
  30. return *this;
  31. }
  32.  
  33. friend std::ostream & operator<<(std::ostream & os, const fp<F> & a) { os << a.s; return os; }
  34. };
  35.  
  36. using fp824 = fp<24>;
  37. using fp1616 = fp<16>;
  38. using fp248 = fp<8>;
  39.  
  40. int main() {
  41. // your code goes here
  42. fp1616 a0(0); // error: ambiguous?!
  43. fp1616 a1(1); // error: ambiguous?!
  44. fp1616 a2(2); // error: ambiguous?!
  45. fp1616 a3(-2.5f);
  46. std::cout << a0 << std::endl;
  47. std::cout << a1 << std::endl;
  48. std::cout << a2 << std::endl;
  49. std::cout << a3 << std::endl;
  50. a0 = 5; // error: ambiguous?!
  51. a0 = 0; // error: ambiguous?!
  52. a0 = 3.4f;
  53. fp824 b1(1.2f);
  54. fp1616 b2(b1);
  55. fp248 b3(b2);
  56. b1 = b3;
  57. b1 = b2;
  58. return 0;
  59. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
0
65536
131072
-163840