fork(5) 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. auto 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 ChainedAdapter(this, next);
  43. }
  44. };
  45.  
  46. class CharIntAdapter : public Adapter<char, int>
  47. {
  48. public:
  49. int adapt(char f) override {
  50. int ret = static_cast<int>(f);
  51. cout << "char('" << f << "') -> int(" << ret << ")" << endl;
  52. return ret;
  53. }
  54. };
  55.  
  56. class IntBoolAdapter : public Adapter<int, bool>
  57. {
  58. public:
  59. bool adapt(int f) override {
  60. bool ret = f != 0;
  61. cout << "int(" << f << ") -> bool(" << boolalpha << ret << ")" << endl;
  62. return ret;
  63. }
  64. };
  65.  
  66. int main() {
  67. CharIntAdapter cia;
  68. cout << cia.adapt('a') << endl;
  69.  
  70. cout << endl;
  71.  
  72. IntBoolAdapter iba;
  73. cout << boolalpha << cia.chain(&iba).adapt('a') << endl;
  74.  
  75. return 0;
  76. }
Success #stdin #stdout 0s 5616KB
stdin
Standard input is empty
stdout
char('a') -> int(97)
97

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