Константы в произвольной системе счисления
Данный набор шаблонов позволяет делать сабж:
Пользоваться:
typedef unsigned long ValueType;
template<bool>
struct assertion;
template<>
struct assertion<true>
{
static const unsigned int dummy = 0;
};
template<int num, int limit>
struct limiter
{
static const unsigned int value = assertion<static_cast<bool>(num < limit)>::dummy + num;
};
template<ValueType val, int base>
struct toDec
{
static const unsigned int value = static_cast<ValueType>(base) > val ?
val
:
base * toDec<val / 10, base>::value + limiter<val % 10, base>::value;
private:
};
template<int base>
struct toDec<0, base>
{
static const unsigned int value = 0;
};
Пользоваться:
int fromBin = toDec<1010101, 2>::value; //=85 int fromTetra = toDec<123, 4>::value; //=27 int fromOct = toDec<768, 8>::value; // compile-time error!
