我正在尝试创建一个通用转换函数,旨在将基数任意数字系统转换为十进制:
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>()), ...);
}
用例如下:
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...>();
}
}
至于十六进制,它包含像A~F
:这样的非数字字符int a = 82ABC_H
,它会给出如下错误:invalid digit A in decimal constant
当然,我可以用于 base->10 的数字系统,但除非我为这些数字系统编写另一个,否则operator ""_H(const char*, std::size_t)
它不能重用 my 。toDecImpl
问题:这里是否有任何优雅的解决方法可以重新toDecImpl
用于包含像十六进制这样的 alpha 的数字系统?