fork download
  1. /** Linked Lists in C++
  2. ** @author Muhammad Ahmad Tirmazi
  3. **/
  4.  
  5. #include <string>
  6. #include <iostream>
  7. #include <vector>
  8. #include <typeinfo>
  9.  
  10. using namespace std;
  11.  
  12. struct element
  13. {
  14. element(void* obj, std::type_info const* t): object(obj), type(t) {}
  15. void* object;
  16. std::type_info const* type;
  17. };
  18.  
  19. class linked_list
  20. {
  21. std::vector< element* > stack;
  22. public:
  23. linked_list() {}
  24. virtual ~linked_list() {}
  25.  
  26. template<typename T> void add_element(T* obj)
  27. {
  28. void* v_obj = static_cast< void* >( obj );
  29. stack.push_back( new element( v_obj, &typeid(obj) ) );
  30. }
  31.  
  32. template < typename T > T* get_element( int index )
  33. {
  34. if ( *stack[index]->type == typeid(T*) )
  35. {
  36. return static_cast<T*>( stack[index]->object );
  37. }
  38.  
  39. else throw 1;
  40. }
  41. };
  42.  
  43. int main()
  44. {
  45. linked_list list;
  46.  
  47. int i = 5;
  48. cout << i << endl;
  49.  
  50. list.add_element( &i );
  51. list.add_element( new string("Hello!") );
  52.  
  53. try{
  54. int* j = list.get_element<int>(0);
  55. cout << *j << endl;
  56.  
  57. cout << *list.get_element<string>(1) << endl;
  58. } catch(...){ cout << "ERROR!" << endl; }
  59. }
Success #stdin #stdout 0s 2964KB
stdin
Standard input is empty
stdout
5
5
Hello!