fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct Base
  5. {
  6. virtual void exec() { std::cout << "base" << std::endl; }
  7. virtual ~Base() { }
  8. };
  9.  
  10. struct Derived1 : public Base
  11. {
  12. void exec() override { std::cout << "derived1" <<std::endl; }
  13. };
  14.  
  15. struct Derived2 : public Base
  16. {
  17. void exec() override { std::cout << "derived2" << std::endl; }
  18. };
  19.  
  20. template<typename T> struct Wrapper : public T
  21. {
  22. bool b{true};
  23. using T::T;
  24. };
  25.  
  26. template<typename T> auto& asWrapper(T& mX)
  27. {
  28. return static_cast<Wrapper<T>&>(mX);
  29. }
  30.  
  31. template<typename T, typename TWrapper> auto& asT(TWrapper& mX)
  32. {
  33. return reinterpret_cast<T&>(mX);
  34. }
  35.  
  36. int main()
  37. {
  38. auto d1 = std::make_unique<Wrapper<Derived1>>();
  39. auto d2 = std::make_unique<Wrapper<Derived2>>();
  40.  
  41. Base* bd1 = d1.get();
  42. Base* bd2 = d2.get();
  43.  
  44. bd1->exec();
  45. bd2->exec();
  46.  
  47. auto& bl1 = asWrapper(*bd1);
  48. auto& bl2 = asWrapper(*bd2);
  49.  
  50. std::cout << bl1.b << " " << bl2.b << std::endl;
  51. bl1.b = false;
  52. std::cout << bl1.b << " " << bl2.b << std::endl;
  53. bl2.b = false;
  54. std::cout << bl1.b << " " << bl2.b << std::endl;
  55.  
  56. asT<Derived1>(bl1).exec();
  57. asT<Derived2>(bl2).exec();
  58.  
  59. return 0;
  60. }
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
derived1
derived2
1 1
0 1
0 0
derived1
derived2