grains: with std::conditional

This commit is contained in:
Dmitry Kokorin 2016-03-16 15:37:48 +03:00
parent 2458db6091
commit 1e20c23729

View file

@ -1,18 +1,56 @@
#include "grains.h" #include "grains.h"
#include <limits>
#include <stdexcept>
namespace grains { namespace grains {
using namespace std;
namespace {
static const index_t number_of_squares = 64; static const index_t number_of_squares = 64;
template <typename T>
struct total_as_max
{
static inline T total()
{
return numeric_limits<T>::max();
}
};
template <typename T>
struct total_by_shift
{
static inline T total()
{
return T(1) << number_of_squares - 1;
}
};
static_assert(number_of_squares <= numeric_limits<ulong_t>::digits,
"grains::ulong_t is too small for grains::total");
typedef conditional<number_of_squares == numeric_limits<ulong_t>::digits,
total_as_max<ulong_t>,
total_by_shift<ulong_t>>::type total_policy_t;
}
ulong_t square(index_t index) ulong_t square(index_t index)
{ {
return 1ULL << (index - 1); if (index < 1 || index > number_of_squares)
throw domain_error("invalid square number");
return ulong_t(1) << (index - 1);
} }
ulong_t total() ulong_t total()
{ {
return (1ULL << number_of_squares) - 1; return total_policy_t::total();
} }
} }