c++ - 使用 Boost Karma 替换 std::stringstream 进行 double 到 std::string 的转换

标签 c++ performance std boost-spirit

为了提高性能,我希望替换:

template<class T> std::string ToStringFixed(const T x, const unsigned int width = 8)
{
  std::stringstream ss;
  ss << std::setprecision(width) << std::fixed << x;
  return ss.str();
}

通过 Boost Karma 的实现,因为我们的项目已经使用了 Boost,它看起来比上面的简单解决方案有显着的性能提升。

类似于:

std::string ToString(double d)
{
  using boost::spirit::karma::double_;
  using boost::spirit::ascii::space;
  using boost::spirit::karma::generate;

  std::string s
  std::back_insert_iterator<std::string> sink(s);
  generate(sink, double_, d);
  return s;
}

取自:http://thisthread.blogspot.com/2011/04/generating-text-with-spirit-karma.html似乎在正确的轨道上,但我不清楚如何控制精度,或者这样的解决方案是否可以在不使用类型特征的情况下对浮点类型模板友好。 (使用 up 到 C++14 的答案是可以接受的。)

最佳答案

您可以在 real_generator 's formatting policies 的帮助下实现您想要的目标.由于您只需要修改可以从默认值 real_policies<Num> 得出的精度然后添加 precision(Num n)具有您需要的行为的成员函数。

Running on WandBox

#include <iostream>
#include <string>
#include <cmath>

#include <boost/spirit/include/karma.hpp>

template <typename Num>
struct precision_policy : boost::spirit::karma::real_policies<Num>
{
    precision_policy(int prec):precision_(prec){}
    int precision(Num n) const { return precision_; }
    int precision_;
};

std::string ToStringFixedKarma(double d, const unsigned int width = 8)
{
  using boost::spirit::karma::real_generator;
  using boost::spirit::ascii::space;
  using boost::spirit::karma::generate;

  real_generator<double,precision_policy<double> > my_double_(width);

  std::string s;
  std::back_insert_iterator<std::string> sink(s);
  generate(sink, my_double_, d);
  return s;
}

int main() {
    const double pi = std::acos(-1);
    std::cout << ToStringFixedKarma(pi) << std::endl;
    std::cout << ToStringFixedKarma(pi,2) << std::endl;
    std::cout << ToStringFixedKarma(pi,4) << std::endl;
}

PS:文档(和检查源代码)似乎暗示这些策略中的成员函数需要是静态的,这将使您无法实现所需,但是 this example事实并非如此。

关于c++ - 使用 Boost Karma 替换 std::stringstream 进行 double 到 std::string 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255919/

相关文章:

c++ - 加载共享库时 undefined symbol "tbb internal Allocate"

c++ - 指向一个索引的pointed

c++ - 此 strncpy 存在哪些安全问题?

python - 将字典转换为平面数据结构(列表或元组)的有效方法

performance - 32 字节对齐例程不适合 uops 缓存

c++ - 非静态成员函数的 std::add_pointer 实现

c++ - 什么是 std::views::counted?

c++ - 从 C++ 中的 vector 获取指针 vector

c++ - 何时使用 std::string 与 char*?

linux - 如何将时钟周期中的进程 cpu 使用率转换为百分比?