| 1 | // -*- C++ -*- |
| 2 | |
| 3 | /** |
| 4 | * @file checkpoweroftwo.h |
| 5 | * @brief Check statically if a number is a power of two. |
| 6 | * @author Emery Berger <http://www.cs.umass.edu/~emery> |
| 7 | * @note Copyright (C) 2005 by Emery Berger, University of Massachusetts Amherst. |
| 8 | * |
| 9 | **/ |
| 10 | |
| 11 | |
| 12 | #ifndef HL_CHECKPOWEROFTWO_H |
| 13 | #define HL_CHECKPOWEROFTWO_H |
| 14 | |
| 15 | /** |
| 16 | * @class IsPowerOfTwo |
| 17 | * @brief Sets value to 1 iff the template argument is a power of two. |
| 18 | * |
| 19 | **/ |
| 20 | |
| 21 | namespace HL { |
| 22 | |
| 23 | template <unsigned long Number> |
| 24 | class IsPowerOfTwo { |
| 25 | public: |
| 26 | enum { VALUE = (!(Number & (Number - 1)) && Number) }; |
| 27 | }; |
| 28 | |
| 29 | /** |
| 30 | * @class CheckPowerOfTwo |
| 31 | * @brief Template meta-program: fails if number is not a power of two. |
| 32 | * |
| 33 | **/ |
| 34 | template <unsigned long V> |
| 35 | class CheckPowerOfTwo { |
| 36 | public: |
| 37 | CheckPowerOfTwo() { |
| 38 | static_assert(IsPowerOfTwo<V>::VALUE, "Argument must be a power of two."); |
| 39 | } |
| 40 | // enum { Verify = HL::sassert<IsPowerOfTwo<V>::VALUE>::VALUE }; |
| 41 | }; |
| 42 | |
| 43 | } |
| 44 | |
| 45 | #endif |