项目作者: yanghuan

项目描述 :
Reflection in C++
高级语言: C++
项目地址: git://github.com/yanghuan/Reflection_C_plus_plus.git
创建时间: 2012-11-11T13:09:16Z
项目社区:https://github.com/yanghuan/Reflection_C_plus_plus

开源协议:Apache License 2.0

下载


Refection C++

One simple implementation of C++ refection.

Introduction

  • Use C++ template metaprogramming techniques(Boost.MPL)
  • Generated during compilation metadata stored in read-only data area
  • Need boost library and GCC 4.7 or later

Sample

  1. #include <cstdlib>
  2. #include <cstring>
  3. #include <iostream>
  4. #include <tuple>
  5. #include <type_traits>
  6. #include <functional>
  7. #include <boost/mpl/at.hpp>
  8. #include <boost/mpl/vector.hpp>
  9. #include <boost/mpl/sort.hpp>
  10. #include "refection/method_wrap.hpp"
  11. #include "utility.hpp"
  12. using namespace std;
  13. using namespace boost;
  14. using namespace refection;
  15. namespace test {
  16. struct AA : public refection::Object
  17. {
  18. public:
  19. REFECTION_CLASS_DECLARE();
  20. public:
  21. void f() {}
  22. static int aa() {
  23. cout << "aa function is invoke" << endl;
  24. return 10;
  25. }
  26. void e(int) {
  27. cout << "e function is invoke" << endl;
  28. }
  29. };
  30. REFECTION_CLASS_IMPLEMENT_BEGIN(AA)
  31. REFECTION_METHOD_IMPLEMENT(f, void(AA::*)()),
  32. REFECTION_METHOD_IMPLEMENT(e, void(AA::*)(int)),
  33. REFECTION_METHOD_IMPLEMENT(aa, int(*)()),
  34. REFECTION_CLASS_IMPLEMENT_END()
  35. } // namespace test
  36. void test1() {
  37. test::AA aa;
  38. const Type& t = aa.getType();
  39. const MethodInfo* array = t.package_.method_list_;
  40. const size_t size = t.package_.method_list_size_;
  41. /* show function info */
  42. for(size_t i = 0 ; i < size; ++i) {
  43. cout << getDemangleString(array[i].declaring_type_.package_.type_info_.name()) << endl;
  44. cout << getDemangleString(array[i].signature_.name()) << endl;
  45. cout << array[i].name_ << endl;
  46. cout << array[i].declaring_type_.package_.name_ << endl;
  47. cout << reinterpret_cast<const void*>(array[i].ptr_.func_ptr) << endl;
  48. }
  49. /* invoke function */
  50. const MethodInfo* func = t.getMethod("e");
  51. if(func != nullptr) {
  52. func->invoke<void>(&aa,30);
  53. }
  54. func = t.getMethod("aa");
  55. if (func != nullptr) {
  56. int resoult = func->invoke<int>(nullptr);
  57. cout << "resoult:" << resoult << endl;
  58. }
  59. }

Note

It’s very simple, just do the technical principle show.