fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. class YObject {
  7. const string m_name;
  8. public:
  9. YObject(const string& name) : m_name(name) {}
  10. virtual const string& getName() { return m_name; }
  11. };
  12.  
  13. class UIButton : public YObject {
  14. public:
  15. UIButton(const string& name) : YObject(name) {}
  16. };
  17.  
  18. class ObjectType : public YObject {
  19. public:
  20. ObjectType(const string& name) : YObject(name) {}
  21. };
  22.  
  23. vector<YObject*> foo;
  24.  
  25. template <typename T>
  26. T* object_of() {
  27. T* result = nullptr;
  28.  
  29. for (auto& i : foo) {
  30. T* bar = dynamic_cast<T*>(i);
  31.  
  32. if (bar != nullptr) {
  33. result = bar;
  34. }
  35. }
  36. return result;
  37. }
  38.  
  39. int main() {
  40. foo.push_back(new UIButton("1"));
  41. foo.push_back(new ObjectType("2"));
  42. foo.push_back(new UIButton("3"));
  43.  
  44. cout << object_of<UIButton>()->getName() << endl;
  45. cout << object_of<ObjectType>()->getName() << endl;
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
3
2