fork(2) download
  1. #include <iostream>
  2. #include <type_traits>
  3.  
  4. class SubType {};
  5.  
  6. class A : SubType {
  7. // things
  8. };
  9.  
  10. class B : public A {
  11. // more things
  12. };
  13.  
  14. class SubBase {
  15. /* default impl. */
  16. public:
  17. virtual A* get() = 0;
  18.  
  19. };
  20.  
  21. template <typename T>
  22. class Base : public SubBase {
  23. public:
  24. Base(SubType* subinst) :instance((void*)subinst) {}
  25. Base(void* inst) :instance(inst) {}
  26. Base(T* t) :Base(dynamic_cast<A*>(t)) {}
  27. public:
  28. void* instance;
  29.  
  30. };
  31.  
  32. template <typename T, typename = typename std::is_base_of<T, A>::type>
  33. class Wrapper : public Base<T> {
  34. public:
  35. Wrapper(T* t) :Base<T>(static_cast<void*>(t)) {}
  36. virtual T* get() { return (T*)Base<T>::instance; }
  37. };
  38.  
  39. class Worker {
  40. public:
  41. void work(Wrapper<A>* wa){
  42. A* a = wa->get();
  43. //do stuff with a.
  44. }
  45. };
  46.  
  47. int main() {
  48. B b;
  49. Worker worker;
  50. Wrapper<B> wrapped_b(&b);
  51. worker.work((Wrapper<A>*)&wrapped_b);
  52. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty