You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.2KB

  1. #ifndef _REFLECTOR_H
  2. #define _REFLECTOR_H
  3. #include <map>
  4. #include <string>
  5. #include <functional>
  6. #include <iostream>
  7. #include <memory>
  8. #include <vector>
  9. class Reflector{
  10. public:
  11. typedef std::function<int(int argc, char const *argv[])> FuncType;
  12. private:
  13. std::map<std::string, std::pair<std::string, FuncType>> objectMap;
  14. public:
  15. std::vector<std::string> getAllRegisterFun(){
  16. std::vector<std::string> re;
  17. for(auto& x : objectMap){
  18. re.push_back(x.second.first);
  19. }
  20. return re;
  21. }
  22. bool registerFun(const char* name, const std::string& proto, FuncType && generator){
  23. assert(objectMap.find(name) == objectMap.end());
  24. objectMap[name] = std::make_pair(proto, generator);
  25. return true;
  26. }
  27. bool runFun(const char* name, int argc, char const *argv[]){
  28. auto ptr = objectMap.find(name);
  29. if(ptr == objectMap.end()){
  30. std::cout << "err! not find "<< name << std::endl;
  31. return false;
  32. }
  33. ptr->second.second(argc, argv);
  34. return true;
  35. }
  36. static Reflector* Instance(){
  37. static Reflector ptr;
  38. return &ptr;
  39. }
  40. };
  41. #endif