fork(3) download
  1. #include <iostream>
  2. using namespace std;
  3. class RigidBody{
  4. float position=1;
  5. public: float getPosition()const{ return position;}
  6. public: void setPosition(float ppos){ position=ppos;}
  7. };
  8. class Adaptor{
  9. RigidBody const& body;
  10. int offset;
  11.  
  12. Adaptor(RigidBody body, int offset=2)
  13. : body(body),
  14. offset(offset)
  15. {}
  16. protected:
  17. RigidBody& get_body() { return const_cast<RigidBody&>(body); }
  18. RigidBody const& get_body() const { return body; }
  19. public:
  20. static Adaptor *adapt(RigidBody& body, int offset = 2) { return new Adaptor{ body, offset }; }
  21. static Adaptor const *adapt(RigidBody const& body, int offset = 2) { return new Adaptor{ body, offset }; }
  22. float getPosition() const
  23. {
  24. // this uses the const get_body()
  25. return get_body().getPosition() + offset;
  26. }
  27.  
  28. void setPosition(float ppos)
  29. {
  30. // this uses the mutable get_body()
  31. get_body().setPosition(ppos-offset);
  32. }
  33. };
  34.  
  35. int main()
  36. {
  37. {
  38. RigidBody b;
  39. auto *a = Adaptor::adapt(b);
  40. a->setPosition(15.);
  41. a->getPosition();
  42. }
  43.  
  44. /*{
  45.   RigidBody const b;
  46.   auto *a = Adaptor::adapt(b);
  47.   a->setPosition(15.); // error: passing ‘const Adaptor’ as ‘this’ argument discards qualifiers
  48.   a->getPosition();
  49.   }*/
  50. }
  51.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty