fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template < int levels1, int levels2 >
  5. class PWMLevelsToType2 {
  6. public:
  7. typedef uint16_t levels_t;
  8. };
  9.  
  10. template < int levels1 >
  11. class PWMLevelsToType2< levels1, 0 > {
  12. public:
  13. typedef uint8_t levels_t;
  14. };
  15.  
  16. template < int levels >
  17. class PWMLevelsToType {
  18. public:
  19. typedef typename PWMLevelsToType2< levels % 256, levels / 256 >::levels_t levels_t;
  20. static inline void advance(levels_t & val) {
  21. ++val;
  22. if (val == levels)
  23. val = 0;
  24. }
  25. };
  26.  
  27. template < int pwm_levels >
  28. class test {
  29. public:
  30. static void do_test() {
  31. typename PWMLevelsToType<pwm_levels>::levels_t levels = pwm_levels - 1;
  32. std::cout << pwm_levels << ": sizeof(levels) = " << sizeof(levels) << ", levels = " << static_cast<int>(levels);
  33. PWMLevelsToType<pwm_levels>::advance(levels);
  34. std::cout << ", after advance(levels) = " << static_cast<int>(levels);
  35. PWMLevelsToType<pwm_levels>::advance(levels);
  36. std::cout << ", again = " << static_cast<int>(levels) << std::endl;
  37. }
  38. };
  39.  
  40. int main() {
  41. test<100>::do_test();
  42. test<101>::do_test();
  43. test<255>::do_test();
  44. test<256>::do_test();
  45. test<512>::do_test();
  46. test<513>::do_test();
  47. test<65535>::do_test();
  48. return 0;
  49. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
100: sizeof(levels) = 1, levels = 99, after advance(levels) = 0, again = 1
101: sizeof(levels) = 1, levels = 100, after advance(levels) = 0, again = 1
255: sizeof(levels) = 1, levels = 254, after advance(levels) = 0, again = 1
256: sizeof(levels) = 2, levels = 255, after advance(levels) = 0, again = 1
512: sizeof(levels) = 2, levels = 511, after advance(levels) = 0, again = 1
513: sizeof(levels) = 2, levels = 512, after advance(levels) = 0, again = 1
65535: sizeof(levels) = 2, levels = 65534, after advance(levels) = 0, again = 1