4

这个问题是因为这个而被问到的。

C++11 允许你为数字文字定义这样的文字:

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

这意味着这503_suffix将成为<'5','0','3'>

这很好,虽然它的形式不是很有用。

如何将其转换回数字类型?这将<'5','0','3'>变成一个constexpr 503. 此外,它还必须适用于浮点文字。<'5','.','3>会变成int 5float 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
4

2 回答 2

4

总是有简单的方法。非类型参数包可以扩展为初始化列表,如下所示:

#include <iostream>

template<char... Chars>
  double
  operator "" _suffix()
  {
    const char str[]{Chars..., '\0'};
    return atof(str);
  }

int
main()
{
  std::cout << 123.456789_suffix << std::endl;
}
于 2011-11-13T05:37:11.690 回答
3

我认为以下内容应该适用于没有指数部分的浮点数(未经测试):

template<bool fp, long long num, long long denom, char ...> struct literal;

template<bool fp, long long num, long long denom> struct literal<fp, num, denom>
{
   static constexpr double value() { return (1.0*num)/denom; }
};

template<long long num, long long denom, char digit, char... rest>
  struct literal<false, num, denom, digit, rest...>
{
  static constexpr double value()
  {
    return literal<false, 10*num + (digit-'0'), denom, rest...>::value();
  }
};

template<long long num, long long denom, char digit, char... rest>
  struct literal<true, num, denom, digit, rest...>
{
  static constexpr double value()
  {
    return literal<true, 10*num + (digit-'0'), 10*denom, rest...>::value();
  }
};

template<long long num, long long denom, char... rest>
  struct literal<false, num, denom, '.', rest...>
{
  static constexpr double value()
  {
    return literal<true, num, denom, rest...>::value();
  }
};

template<char... c> double operator "" _dbl()
{
  return literal<false, 0, 1, c...>::value();
}

如何将其扩展为指数部分应该是显而易见的。

当然,人们还想做一些错误检查(确保字符确实是数字)。

于 2011-11-13T02:12:58.820 回答