Created
June 18, 2015 14:44
-
-
Save garymacindoe/f2e19c82339c103be5f3 to your computer and use it in GitHub Desktop.
Round up to the next highest power of 2 using C++11 compile-time templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <type_traits> | |
#include <limits> | |
template <typename UIntType, UIntType v, unsigned int n> | |
struct set_lower_bits : public std::integral_constant<UIntType, v | (v >> n) | set_lower_bits<UIntType, v | (v >> n), (n >> 1)>::value> {}; | |
template <typename UIntType, UIntType v> | |
struct set_lower_bits<UIntType, v, 1> : public std::integral_constant<UIntType, v | (v >> 1)> {}; | |
template <typename UIntType, UIntType v> | |
struct nextpow2 : public std::integral_constant<UIntType, set_lower_bits<UIntType, v - 1, (std::numeric_limits<UIntType>::digits >> 1)>::value + 1> {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment