![]() |
Compile-time integer arithmetic without using templates
I think the new 'constexpr' keyword is actually quite cool. For example
this calculates the integral square root of an integer, rounded up, at compile time. //------------------------------------------------------------------------ #include <cstdint> constexpr std::uint64_t isqrtIter(std::uint64_t value, std::uint64_t low, std::uint64_t high) { return (low < high ? (((low+high)/2) * ((low+high)/2) < value ? isqrtIter(value, (low+high)/2 + 1, high) : isqrtIter(value, low, (low+high)/2)) : low); } constexpr std::uint64_t isqrt(std::uint64_t value) { return isqrtIter(value, 1, UINT32_MAX); } //------------------------------------------------------------------------ This can actually have practical use, for example to create static arrays that have the size of sqrt(constant), which might be useful for some algorithms. |
| All times are GMT. The time now is 08:24 PM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.