Printable.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- Printable.h - Print function helpers -------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the Printable struct.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_PRINTABLE_H
  18. #define LLVM_SUPPORT_PRINTABLE_H
  19. #include <functional>
  20. #include <utility>
  21. namespace llvm {
  22. class raw_ostream;
  23. /// Simple wrapper around std::function<void(raw_ostream&)>.
  24. /// This class is useful to construct print helpers for raw_ostream.
  25. ///
  26. /// Example:
  27. /// Printable printRegister(unsigned Register) {
  28. /// return Printable([Register](raw_ostream &OS) {
  29. /// OS << getRegisterName(Register);
  30. /// });
  31. /// }
  32. /// ... OS << printRegister(Register); ...
  33. ///
  34. /// Implementation note: Ideally this would just be a typedef, but doing so
  35. /// leads to operator << being ambiguous as function has matching constructors
  36. /// in some STL versions. I have seen the problem on gcc 4.6 libstdc++ and
  37. /// microsoft STL.
  38. class Printable {
  39. public:
  40. std::function<void(raw_ostream &OS)> Print;
  41. Printable(std::function<void(raw_ostream &OS)> Print)
  42. : Print(std::move(Print)) {}
  43. };
  44. inline raw_ostream &operator<<(raw_ostream &OS, const Printable &P) {
  45. P.Print(OS);
  46. return OS;
  47. }
  48. } // namespace llvm
  49. #endif
  50. #ifdef __GNUC__
  51. #pragma GCC diagnostic pop
  52. #endif