Printable.h 1.5 KB

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