fork download
  1. #include <array>
  2. #include <cstdint>
  3.  
  4.  
  5. //
  6. // Helpers..
  7. //
  8. template<unsigned> struct IntegerSize;
  9. template<> struct IntegerSize<1> { typedef uint8_t Type; };
  10. template<> struct IntegerSize<2> { typedef uint16_t Type; };
  11. template<> struct IntegerSize<4> { typedef uint32_t Type; };
  12. template<> struct IntegerSize<8> { typedef uint64_t Type; };
  13.  
  14.  
  15. // Calculates the one's complement sum, but without the final bit flip.
  16. // This allows you to call this method multiple times and flip the bits
  17. // yourself after the last call.
  18. template<typename T>
  19. T OnesComplementSum(T t0, T t1)
  20. {
  21. typedef typename IntegerSize<2 * sizeof(T)>::Type TemporaryResult;
  22. static const T cMaxValue = T(-1);
  23. static const unsigned cNumBits = 8 * sizeof(T);
  24.  
  25. TemporaryResult sum = t0;
  26. sum += t1;
  27. while (sum > cMaxValue)
  28. {
  29. sum = (sum >> cNumBits) + (sum & cMaxValue);
  30. }
  31. return static_cast<T>(sum);
  32. }
  33.  
  34.  
  35. template<typename T, typename ...U>
  36. T OnesComplementSum(T head, U ...tail)
  37. {
  38. return OnesComplementSum(head, OnesComplementSum(tail...));
  39. }
  40.  
  41.  
  42. template<unsigned N> std::array<char, N> datum() { return std::array<char, N>(); }
  43.  
  44. int main()
  45. {
  46. int a;
  47. long b;
  48. char c;
  49.  
  50.  
  51. OnesComplementSum(a, b, c);
  52. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'T OnesComplementSum(T, U ...) [with T = char, U = {}]':
prog.cpp:38:62:   instantiated from 'T OnesComplementSum(T, U ...) [with T = long int, U = {char}]'
prog.cpp:38:62:   instantiated from 'T OnesComplementSum(T, U ...) [with T = int, U = {long int, char}]'
prog.cpp:51:27:   instantiated from here
prog.cpp:38:62: error: no matching function for call to 'OnesComplementSum()'
prog.cpp: In function 'T OnesComplementSum(T, U ...) [with T = long int, U = {}]':
prog.cpp:38:62:   instantiated from 'T OnesComplementSum(T, U ...) [with T = int, U = {long int}]'
prog.cpp:38:62:   instantiated from 'T OnesComplementSum(T, U ...) [with T = int, U = {long int, char}]'
prog.cpp:51:27:   instantiated from here
prog.cpp:38:62: error: no matching function for call to 'OnesComplementSum()'
stdout
Standard output is empty