fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <stdexcept>
  4. #include <vector>
  5.  
  6. class C { public: virtual ~C() = default; };
  7. class C0 : public C { public: void print() { std::cout << "C0\n"; } };
  8. class C1 : public C { public: void print() { std::cout << "C1\n"; } };
  9.  
  10.  
  11. class PrintCaller
  12. {
  13. public:
  14. template <typename T>
  15. std::size_t register_class()
  16. {
  17. m.push_back([](C* c) {
  18. auto* p = dynamic_cast<T*>(c);
  19. if (p) {
  20. p->print();
  21. } else {
  22. throw std::runtime_error("Incorrect type");
  23. }
  24. });
  25. return m.size() - 1;
  26. }
  27.  
  28. void print(std::size_t id, C* c) const {
  29. if (id < m.size()) {
  30. m[id](c);
  31. } else {
  32. throw std::runtime_error("invalid id");
  33. }
  34. }
  35.  
  36. private:
  37. std::vector<std::function<void(C*)>> m;
  38. };
  39.  
  40.  
  41. int main()
  42. {
  43. C0 c0;
  44. C1 c1;
  45.  
  46. PrintCaller p;
  47.  
  48. std::size_t id1 = p.register_class<C1>();
  49. std::size_t id0 = p.register_class<C0>();
  50.  
  51. p.print(id0, &c0);
  52. p.print(id1, &c1);
  53. try {
  54. p.print(id1, &c0);
  55. } catch (std::exception& e) {
  56. std::cout << e.what();
  57. }
  58. }
  59.  
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
C0
C1
Incorrect type