Pella86

Untitled

May 6th, 2020
1,477
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct Propriety
  5. {
  6.     std::string m_name;
  7.  
  8.     Propriety(std::string const& name) : m_name(name)
  9.     {
  10.     }
  11. };
  12.  
  13. template<typename T>
  14. class TypedPropriety : public Propriety
  15. {
  16. public:
  17.     TypedPropriety(std::string const& name, T const& data) : Propriety(name), m_data(data)
  18.     {
  19.     }
  20.  
  21.     T get()
  22.     {
  23.         return m_data;
  24.     }
  25.  
  26. private:
  27.     T m_data;
  28. };
  29.  
  30.  
  31. class Proprieties_list{
  32. public:
  33.     Proprieties_list(){}
  34.  
  35.     void add_propriety(Propriety prop)
  36.     {
  37.         std::shared_ptr<Propriety> ptr(&prop);
  38.         propriety_list.push_back(ptr);
  39.     }
  40.  
  41.     // cerca la proprietà con il nome dato nella lista
  42.     template<typename T>
  43.     T get_data(std::string const& name)
  44.     {
  45.         for(auto prop : propriety_list)
  46.         {
  47.             if(prop->m_name == name){
  48.  
  49.                 TypedPropriety<T> p = dynamic_cast< TypedPropriety<T> > (*prop);
  50.  
  51.                 return  p.get();
  52.             }
  53.         }
  54.     }
  55.  
  56.  
  57. private:
  58.     std::vector< std::shared_ptr<Propriety> > propriety_list;
  59. };
  60.  
  61.  
  62.  
  63. int main()
  64. {
  65.     TypedPropriety<int> n_col("col", 10);
  66.     TypedPropriety<double> mean("mean", 1.0);
  67.  
  68.     Proprieties_list plist;
  69.  
  70.     plist.add_propriety(n_col);
  71.     plist.add_propriety(mean);
  72.  
  73.     std::string name("mean");
  74.     std::cout << plist.get_data<double>("mean") << std::endl;
  75.  
  76.     std::cout << "Hello world!" << std::endl;
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment