fork(1) download
  1. #include <cassert>
  2. #include <iostream>
  3.  
  4. template<typename T, typename R=void>
  5. struct ExtMethod {
  6. ExtMethod& operator - () {
  7. return *this;
  8. }
  9.  
  10. template<typename U>
  11. R operator()( U& obj ) {
  12. return static_cast<T*>(this)->operator()( obj );
  13. }
  14. };
  15.  
  16. template<typename Derived>
  17. struct Extendible
  18. {
  19. template<typename T, typename ReturnT>
  20. ReturnT operator < ( ExtMethod<T, ReturnT>& extMethod ) {
  21. return extMethod( static_cast<Derived&>( *this ) );
  22. }
  23. };
  24.  
  25. struct Widget : Extendible<Widget> {
  26. Widget( int size, int weight ) : size( size ), weight( weight ) {}
  27.  
  28. int size;
  29. int weight;
  30. };
  31. struct print : ExtMethod<print> {
  32. void operator()( Widget& w ) {
  33. std::cout << "size: " << w.size << ", weight: " << w.weight << std::endl;
  34. }
  35. };
  36. struct density : ExtMethod<density, float> {
  37. float operator()( Widget& w ) {
  38. return (float)(w.weight / w.size);
  39. }
  40. };
  41.  
  42. int main() {
  43.  
  44. Widget w( 4, 10 );
  45. w<-print();
  46.  
  47. float d = w<-density();
  48. assert( d - 10/4 < 0.01 );
  49. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
size: 4, weight: 10