format.H 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // -*- mode: c++; coding: utf-8 -*-
  2. /// @file format.H
  3. /// @brief Array output formatting, with some generic ostream sugar.
  4. // (c) Daniel Llorens - 2010, 2016-2018
  5. // This library is free software; you can redistribute it and/or modify it under
  6. // the terms of the GNU General Public License as published by the Free
  7. // Software Foundation; either version 3 of the License, or (at your option) any
  8. // later version.
  9. #pragma once
  10. #include <iterator>
  11. #include <iosfwd>
  12. #include <sstream>
  13. namespace ra {
  14. template <class ... A> inline std::string
  15. format(A && ... a)
  16. {
  17. std::ostringstream o; (o << ... << a); return o.str();
  18. }
  19. inline std::string const & format(std::string const & s) { return s; }
  20. enum print_shape_t { defaultshape, withshape, noshape };
  21. template <class A>
  22. struct FormatArray
  23. {
  24. A const & a;
  25. print_shape_t shape;
  26. char const * sep0;
  27. char const * sep1;
  28. char const * sep2;
  29. };
  30. template <class A> inline
  31. FormatArray<A>
  32. format_array(A const & a, char const * sep0=" ", char const * sep1="\n", char const * sep2="\n")
  33. {
  34. return FormatArray<A> { a, defaultshape, sep0, sep1, sep2 };
  35. }
  36. struct shape_manip_t
  37. {
  38. std::ostream & o;
  39. print_shape_t shape;
  40. };
  41. inline shape_manip_t operator<<(std::ostream & o, print_shape_t shape)
  42. {
  43. return shape_manip_t { o, shape };
  44. }
  45. template <class A>
  46. inline std::ostream & operator<<(shape_manip_t const & sm, A const & a)
  47. {
  48. FormatArray<A> fa = format_array(a);
  49. fa.shape = sm.shape;
  50. return sm.o << fa;
  51. }
  52. template <class A>
  53. inline std::ostream & operator<<(shape_manip_t const & sm, FormatArray<A> fa)
  54. {
  55. fa.shape = sm.shape;
  56. return sm.o << fa;
  57. }
  58. } // namespace ra