我正在尝试创建一个通用的转换函数,旨在将基数-任何数制转换为十进制:
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
当然,我可以对基数>10的数字系统使用operator ""_H(const char*, std::size_t),但它不能重用我的toDecImpl,除非我为这些数字系统编写另一个base。
问:对于包含alpha的十六进制数字系统,是否有任何优雅的解决方案可以重用toDecImpl?
发布于 2019-05-09 15:36:44
如果我正确理解了你对“优雅”的定义,不,这是不可能的。用户定义的文本不能更改语法。根据[lex.icon],您可以使用带十六进制数字的0x或0X,也可以只使用不带0x或0X的十进制数字。编译器在将实际内容提供给UDL函数之前对此进行检查。
是的,你当然可以使用字符串文字。在这种情况下,这应该是一种可以接受的解决方法。
https://stackoverflow.com/questions/56053939
复制相似问题