Motivation:
Here is the implementation of converting base-n to decimal:
template<int from, char... Chs>
constexpr int
toDec()
{
int ret{};
return (
(ret *= from, ret += Chs > '9' ? Chs - 'A' + 10 : Chs - '0'), ...);
}
inline namespace literals
{
template<char... Chs>
constexpr int operator"" _B()
{
return toDec<2, Chs...>();
}
template<char... Chs>
constexpr int operator"" _O()
{
return toDec<8, Chs...>();
}
} // namespace literals
It works fine with base-2
and base-8
:
static_assert(111_B == 7);
static_assert(011_B == 3);
static_assert(052 == 52_O);
static_assert(073227 == 73227_O);
But for base-16, because we have non-number char, so numbers like E7_X
won't work(error: use of undeclared identifier 'E7_X'
), so I use user-defined-string-literal
:
constexpr int operator""_X(const char* str, unsigned long)
{
// do something to unpack str into <char...>, so I can reuse toDec;
}
......
static_assert(0XE7 == "E7"_X);
For dry, I hope to reuse toDec
, so I need to unpack str
into <char...>
, do you have any idea? (If you have any elegant solution for the base-16 case, please tell me, I would very appreciate it!)
and with C++14, binary literals are also standard
Yes, I'm aware of it. Here is just a practice and for some reasons, I hope get base-11/12/13/14... convertion