How can variadic char template arguments from user defined literals be converted back into numeric types?

Posted by Pubby on Stack Overflow See other posts from Stack Overflow or by Pubby
Published on 2011-11-13T01:46:13Z Indexed on 2011/11/13 1:51 UTC
Read the original article Hit count: 216

This question is being asked because of this one.

C++11 allows you to define literals like this for numeric literals:

template<char...> OutputType operator "" _suffix();

Which means that 503_suffix would become <'5','0','3'>

This is nice, although it isn't very useful in the form it's in.

How can I transform this back into a numeric type? This would turn <'5','0','3'> into a constexpr 503. Additionally, it must also work on floating point literals. <'5','.','3> would turn into int 5 or float 5.3

A partial solution was found in the previous question, but it doesn't work on non-integers:

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

© Stack Overflow or respective owner

Related posts about c++

Related posts about c++11