fork(1) download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. template<typename FROM, typename TO>
  7. class Adapter
  8. {
  9. public:
  10. /**
  11.   * Adapts something from one type to a type.
  12.   * @param f
  13.   * @return
  14.   */
  15. virtual TO adapt(FROM f) = 0;
  16.  
  17. /**
  18.   * Chains adapters.
  19.   *
  20.   * @param <NEXT>
  21.   * @param next
  22.   * @return a new adapter that takes the output of this adapter and
  23.   * adapts to something of type NEXT.
  24.   */
  25. template<typename NEXT>
  26. std::unique_ptr<Adapter<FROM, NEXT>> chain(Adapter<TO, NEXT> *next)
  27. {
  28. class ChainedAdapter : public Adapter<FROM, NEXT>
  29. {
  30. private:
  31. Adapter<FROM, TO> *x;
  32. Adapter<TO, NEXT> *next;
  33. public:
  34. ChainedAdapter(Adapter<FROM, TO> *x, Adapter<TO, NEXT> *next)
  35. : x(x), next(next) {}
  36.  
  37. NEXT adapt(FROM f) override {
  38. return next->adapt(x->adapt(f));
  39. }
  40. };
  41.  
  42. //return std::make_unique<ChainedAdapter>(this, next);
  43. return std::unique_ptr<ChainedAdapter>(new ChainedAdapter(this, next));
  44. }
  45. };
  46.  
  47. class CharIntAdapter : public Adapter<char, int>
  48. {
  49. public:
  50. int adapt(char f) override {
  51. int ret = static_cast<int>(f);
  52. cout << "char('" << f << "') -> int(" << ret << ")" << endl;
  53. return ret;
  54. }
  55. };
  56.  
  57. class IntBoolAdapter : public Adapter<int, bool>
  58. {
  59. public:
  60. bool adapt(int f) override {
  61. bool ret = f != 0;
  62. cout << "int(" << f << ") -> bool(" << boolalpha << ret << ")" << endl;
  63. return ret;
  64. }
  65. };
  66.  
  67. int main() {
  68. CharIntAdapter cia;
  69. cout << cia.adapt('a') << endl;
  70.  
  71. cout << endl;
  72.  
  73. IntBoolAdapter iba;
  74. cout << boolalpha << cia.chain(&iba)->adapt('a') << endl;
  75.  
  76. return 0;
  77. }
Success #stdin #stdout 0.01s 5496KB
stdin
Standard input is empty
stdout
char('a') -> int(97)
97

char('a') -> int(97)
int(97) -> bool(true)
true