fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4.  
  5. // a dummy QDebug class, don't have QT installed here
  6. class QDebug {};
  7. QDebug& qDebug() {
  8. static QDebug obj;
  9. return obj;
  10. }
  11. template <typename T>
  12. QDebug& operator <<(QDebug &os, const T &value) {
  13. std::cout << "QDebug: " << value << std::endl;
  14. return os;
  15. }
  16. // end dummy class
  17.  
  18.  
  19. class ILoggableValue {
  20. public:
  21. virtual ~ILoggableValue() = default;
  22. virtual void log(QDebug &os) const = 0;
  23. virtual void log(std::ostream &os) const = 0;
  24. };
  25.  
  26. template <typename T>
  27. class LoggableValue : public ILoggableValue {
  28. public:
  29. LoggableValue(const T &value) : value{value} {}
  30. void log(QDebug &os) const override {
  31. // implementation of log for QDebug goes here
  32. os << value;
  33. }
  34. void log (std::ostream &os) const override {
  35. // implementation of log for std::ostream goes here
  36. os << value << std::endl;
  37. }
  38. private:
  39. const T &value;
  40. };
  41.  
  42.  
  43. class IHandler {
  44. public:
  45. virtual ~IHandler() = default;
  46. virtual void log(const ILoggableValue &tolog) const = 0;
  47. };
  48.  
  49. class CLHandler : public IHandler {
  50. public:
  51. explicit CLHandler(std::ostream &out) : out{out} {}
  52. void log(const ILoggableValue &tolog) const override {
  53. tolog.log(out);
  54. }
  55. private:
  56. std::ostream &out;
  57. };
  58.  
  59. class UIHandler : public IHandler {
  60. public:
  61. void log(const ILoggableValue &tolog) const override {
  62. tolog.log(qDebug());
  63. }
  64. };
  65.  
  66.  
  67. class Logger {
  68. public:
  69. Logger(std::unique_ptr<IHandler> h) : handler(std::move(h)) {}
  70. template <class T>
  71. void log(const T& tolog) { handler->log(LoggableValue<T>(tolog)); }
  72.  
  73. void setHandler(std::unique_ptr<IHandler> &h) { handler = std::move(h); }
  74. const IHandler &getHandler() const { return *handler; }
  75.  
  76. private:
  77. std::unique_ptr<IHandler> handler;
  78. };
  79.  
  80.  
  81. // example
  82. void example(Logger &logger) {
  83. logger.log(5);
  84. logger.log("ABC");
  85. logger.log(4.2);
  86. }
  87.  
  88. int main() {
  89. Logger qLogger{std::make_unique<UIHandler>()};
  90. example(qLogger);
  91. Logger stdoutLogger{std::make_unique<CLHandler>(std::cout)};
  92. example(stdoutLogger);
  93. }
  94.  
Success #stdin #stdout 0s 4140KB
stdin
Standard input is empty
stdout
QDebug: 5
QDebug: ABC
QDebug: 4.2
5
ABC
4.2