#include <iostream> using namespace std; template < int levels1, int levels2 > class PWMLevelsToType2 { public: typedef uint16_t levels_t; }; template < int levels1 > class PWMLevelsToType2< levels1, 0 > { public: typedef uint8_t levels_t; }; template < int levels > class PWMLevelsToType { public: typedef typename PWMLevelsToType2< levels % 256, levels / 256 >::levels_t levels_t; static inline void advance(levels_t & val) { ++val; if (val == levels) val = 0; } }; template < int pwm_levels > class test { public: static void do_test() { typename PWMLevelsToType<pwm_levels>::levels_t levels = pwm_levels - 1; std::cout << pwm_levels << ": sizeof(levels) = " << sizeof(levels) << ", levels = " << static_cast<int>(levels); PWMLevelsToType<pwm_levels>::advance(levels); std::cout << ", after advance(levels) = " << static_cast<int>(levels); PWMLevelsToType<pwm_levels>::advance(levels); std::cout << ", again = " << static_cast<int>(levels) << std::endl; } }; int main() { test<100>::do_test(); test<101>::do_test(); test<255>::do_test(); test<256>::do_test(); test<512>::do_test(); test<513>::do_test(); test<65535>::do_test(); return 0; }
Standard input is empty
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