I'm trying to create a universal conversion function which aims to convert base-any numeral system to decimal:
namespace detail
{
template<char Chs> constexpr auto
toDecImpl()
{
return Chs > '9' ? Chs - 'A' + 10 : Chs - '0';
}
} // namespace detail
template<int from, char... Chs> constexpr auto
toDec()
{
int ret{};
return ((ret *= from, ret += detail::toDecImpl<Chs>()), ...);
}
And the use case is like:
inline namespace literals
{
template<char... Chs> constexpr auto
operator"" _B()
{
return toDec<2, Chs...>();
}
template<char... Chs> constexpr auto
operator"" _O()
{
return toDec<8, Chs...>();
}
template<char... Chs> constexpr auto
operator"" _H()
{
return toDec<16, Chs...>();
}
}
As for heximal, which contains non-digit char likeA~F
: int a = 82ABC_H
, and it will give an error like: invalid digit A in decimal constant
Of course, I can use operator ""_H(const char*, std::size_t)
for base- >10 number system, but it cannot re-use my toDecImpl
unless I write another one for these number systems.
Question: Is there any elegant workaround here to re-use toDecImpl
for number system that contain alpha like hex?