fork download
  1. // A simple example using type-erasure.
  2.  
  3. #include <iostream>
  4. #include <vector>
  5. #include <memory>
  6.  
  7. class Example {
  8. struct _Concept {
  9. virtual ~_Concept() = default;
  10. virtual const char* f() const = 0;
  11. };
  12.  
  13. template<typename T>
  14. struct _Model : _Concept {
  15. _Model(T* p)
  16. : m_p(p)
  17. {}
  18. const char* f() const
  19. { return m_p->f(); }
  20. private:
  21. T* m_p;
  22. };
  23.  
  24. std::vector<std::unique_ptr<_Concept>> m_items;
  25.  
  26. public:
  27. template<typename T>
  28. void add_item(T* p)
  29. {
  30. m_items.push_back(std::make_unique<_Model<T>>(p));
  31. }
  32.  
  33. void process_items()
  34. {
  35. for (const auto& x : m_items)
  36. std::cout << x->f() << std::endl;
  37. }
  38. };
  39.  
  40. // Use.
  41.  
  42. struct A {
  43. const char* f()
  44. { return "A::f"; }
  45. };
  46.  
  47. struct B {
  48. const char* f()
  49. { return "B::f"; }
  50. };
  51.  
  52. int main()
  53. {
  54. Example x;
  55. A a;
  56. B b;
  57. x.add_item(&a);
  58. x.add_item(&b);
  59. x.process_items();
  60. }
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout
A::f
B::f