class_name.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (c) 2011 Baidu.com, Inc. All Rights Reserved
  2. //
  3. // Get name of a class. For example, class_name<T>() returns the name of T
  4. // (with namespace prefixes). This is useful in template classes.
  5. //
  6. // Author: Ge,Jun (gejun@baidu.com)
  7. // Date: Mon. Nov 7 14:47:36 CST 2011
  8. #ifndef BRPC_BASE_CLASS_NAME_H
  9. #define BRPC_BASE_CLASS_NAME_H
  10. #include <typeinfo>
  11. #include <string> // std::string
  12. namespace base {
  13. std::string demangle(const char* name);
  14. namespace detail {
  15. template <typename T> struct ClassNameHelper { static std::string name; };
  16. template <typename T> std::string ClassNameHelper<T>::name = demangle(typeid(T).name());
  17. }
  18. // Get name of class |T|, in std::string.
  19. template <typename T> const std::string& class_name_str() {
  20. // We don't use static-variable-inside-function because before C++11
  21. // local static variable is not guaranteed to be thread-safe.
  22. return detail::ClassNameHelper<T>::name;
  23. }
  24. // Get name of class |T|, in const char*.
  25. // Address of returned name never changes.
  26. template <typename T> const char* class_name() {
  27. return class_name_str<T>().c_str();
  28. }
  29. // Get typename of |obj|, in std::string
  30. template <typename T> std::string class_name_str(T const& obj) {
  31. extern std::string demangle(const char* name);
  32. return demangle(typeid(obj).name());
  33. }
  34. } // namespace base
  35. #endif // BRPC_BASE_CLASS_NAME_H