fork download
  1.  
  2. #include <map>
  3. #include <tuple>
  4. #include <string>
  5. #include <typeinfo>
  6.  
  7. #define REGISTER_ELEM( ELEM ) \
  8.   { Reflectable* p = this; } \
  9.   register_element( #ELEM, typeid(ELEM).name(), &ELEM )
  10.  
  11.  
  12. struct Reflectable {
  13.  
  14. public:
  15. class Caster {
  16. public:
  17. Caster(void* ptr) : m_ptr(ptr) {}
  18. Caster() {}
  19.  
  20. template<typename T> operator T&() {
  21. return *reinterpret_cast<T*>(m_ptr);
  22. }
  23.  
  24. private:
  25. void* m_ptr;
  26.  
  27. };
  28.  
  29. Caster& get(const std::string key) {
  30. return std::get<1>(m_elements.at(key));
  31. }
  32.  
  33. std::string type(const std::string key) {
  34. return std::get<0>(m_elements.at(key));
  35. }
  36.  
  37. protected:
  38. void register_element(const std::string key, const std::string type_name, void* ptr) {
  39. m_elements[key] = std::make_tuple(type_name, Caster(ptr));
  40. }
  41.  
  42. private:
  43.  
  44. std::map<const std::string, std::tuple<std::string, Caster>> m_elements;
  45. };
  46.  
  47.  
  48. // main.cpp
  49.  
  50. #include <iostream>
  51.  
  52. struct Test : Reflectable {
  53. int a = 123;
  54. double b = 256;
  55.  
  56. Test() {
  57. REGISTER_ELEM(a);
  58. REGISTER_ELEM(b);
  59. }
  60. };
  61.  
  62. int main(void) {
  63. Test test;
  64.  
  65. int a = test.get("a");
  66. double b = test.get("b");
  67. std::cout << "a is " << a << std::endl;
  68. std::cout << "b is " << b << std::endl;
  69. }
  70.  
  71.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
a is 123
b is 256