这个问题是因为这个而被问到的。
C++11 允许你为数字文字定义这样的文字:
template<char...> OutputType operator "" _suffix();
这意味着这503_suffix
将成为<'5','0','3'>
这很好,虽然它的形式不是很有用。
如何将其转换回数字类型?这将<'5','0','3'>
变成一个constexpr
503
. 此外,它还必须适用于浮点文字。<'5','.','3>
会变成int 5
或float 5.3
在上一个问题中找到了部分解决方案,但它不适用于非整数:
template <typename t>
constexpr t pow(t base, int exp) {
return (exp > 0) ? base * pow(base, exp-1) : 1;
};
template <char...> struct literal;
template <> struct literal<> {
static const unsigned int to_int = 0;
};
template <char c, char ...cv> struct literal<c, cv...> {
static const unsigned int to_int = (c - '0') * pow(10, sizeof...(cv)) + literal<cv...>::to_int;
};
// use: literal<...>::to_int
// literal<'1','.','5'>::to_int doesn't work
// literal<'1','.','5'>::to_float not implemented