fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. //---------------------------------------------------------
  5.  
  6. template <typename TDerivedClass>
  7. class AbstractLogger {
  8. public:
  9. void write(int x);
  10. void write(double x);
  11.  
  12. template <typename T>
  13. void writeLine(T x);
  14. };
  15.  
  16. template <typename TDerivedClass>
  17. void AbstractLogger<TDerivedClass>::write(int x) {
  18. std::cout << x;
  19. }
  20.  
  21. template <typename TDerivedClass>
  22. void AbstractLogger<TDerivedClass>::write(double x) {
  23. std::cout << std::setprecision(3) << x;
  24. }
  25.  
  26. template <typename TDerivedClass>
  27. template <typename T>
  28. void AbstractLogger<TDerivedClass>::writeLine(T x) {
  29. static_cast<TDerivedClass*>(this)->write(x);
  30. std::cout << std::endl;
  31. }
  32.  
  33. //---------------------------------------------------------
  34.  
  35. class Logger : public AbstractLogger<Logger> {};
  36.  
  37. //---------------------------------------------------------
  38.  
  39. class FooType1 {};
  40. class FooType2 {};
  41.  
  42. class FooLogger : public AbstractLogger<FooLogger> {
  43. public:
  44. using AbstractLogger::write;
  45.  
  46. void write(FooType1 x);
  47. void write(FooType2 x);
  48. };
  49.  
  50.  
  51. void FooLogger::write(FooType1 x) {
  52. std::cout << "<value of type FooType1>";
  53. }
  54. void FooLogger::write(FooType2 x) {
  55. std::cout << "<value of type FooType2>";
  56. }
  57.  
  58. //---------------------------------------------------------
  59.  
  60. int main(int argc, char **argv) {
  61. FooLogger log;
  62. FooType1 foo1;
  63. FooType2 foo2;
  64.  
  65. log.write(42); // OK
  66. log.write(3.14159); // OK
  67. log.write(foo1); // OK
  68. log.write(foo2); // OK
  69.  
  70. std::cout << std::endl;
  71.  
  72. log.writeLine(42); // OK
  73. log.writeLine(3.14159); // OK
  74. log.writeLine(foo1); // OK
  75. log.writeLine(foo2); // OK
  76. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
423.14<value of type FooType1><value of type FooType2>
42
3.14
<value of type FooType1>
<value of type FooType2>