fork(1) download
  1. #include <memory>
  2.  
  3. class generic {
  4. class underlying_base {
  5. public:
  6. virtual ~underlying_base(){}
  7. virtual void SomeGenericMethod()=0;
  8. };
  9. template <class T>
  10. class underlying_impl : public underlying_base {
  11. T data;
  12. public:
  13. underlying_impl(const T& d) :data(d) {}
  14. virtual void SomeGenericMethod()
  15. {return data.SomeGenericMethod();}
  16. };
  17. public:
  18. std::unique_ptr<underlying_base> data;
  19.  
  20. template < class T > void setOther(const T& other) {
  21. data.reset(new underlying_impl<T>(other));
  22. }
  23.  
  24. void doSomethingWithOther() {
  25. data->SomeGenericMethod();
  26. }
  27. };
  28.  
  29. #include <iostream>
  30. struct Bar {
  31. void SomeGenericMethod() {std::cout << "BAR\n";}
  32. };
  33.  
  34. int main(int argc, char **argv) {
  35. generic fObj;
  36. Bar bObj;
  37. fObj.setOther(bObj);
  38. fObj.doSomethingWithOther();
  39. return 0;
  40. }
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
BAR