fork download
  1. #include <memory>
  2. #include <iostream>
  3.  
  4. struct base
  5. {
  6. using ptr = std::shared_ptr<base> ;
  7.  
  8. base( int i ) : a(i) {}
  9. virtual ~base() {}
  10.  
  11. virtual ptr plus( int i ) const { return std::make_shared<base>( a+i ) ; }
  12.  
  13. virtual std::ostream& print( std::ostream& stm ) const
  14. { return stm << "base{" << a << '}' ; }
  15.  
  16. int a ;
  17. };
  18.  
  19. struct derived : base
  20. {
  21. derived( int i, int j ) : base(i), b(j) {}
  22.  
  23. virtual ptr plus( int i ) const override
  24. { return std::make_shared<derived>( a+i, b+i ) ; }
  25.  
  26. virtual std::ostream& print( std::ostream& stm ) const
  27. { return stm << "derived{" << a << ',' << b << '}' ; }
  28.  
  29. int b ;
  30. };
  31.  
  32. struct surrogate
  33. {
  34. // in real life, we may need to colour constructors
  35. surrogate( int i ) : p( std::make_shared<base>(i) ) {}
  36. surrogate( int i, int j ) : p( std::make_shared<derived>(i,j) ) {}
  37.  
  38. surrogate( base::ptr pp ) : p(pp) {}
  39.  
  40. base::ptr p ;
  41. };
  42.  
  43. surrogate operator+ ( const surrogate& s, int i ) { return s.p->plus(i) ; }
  44. surrogate operator+ ( int i, const surrogate& s ) { return s + i ; }
  45. std::ostream& operator<< ( std::ostream& stm, const surrogate& s )
  46. { return s.p->print(stm) ; }
  47.  
  48. int main()
  49. {
  50. surrogate a(100), b(200,300) ;
  51. std::cout << "a: " << a << " a+1234: " << a+1234 << '\n' ;
  52. std::cout << "b: " << b << " 5678+b: " << 5678+b << '\n' ;
  53. }
  54.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
a: base{100}  a+1234: base{1334}
b: derived{200,300}  5678+b: derived{5878,5978}