How can I get the class name from a C++ object?

前端 未结 8 2175
名媛妹妹
名媛妹妹 2020-11-29 20:56

Is it possible to get the object name too?

#include

class one {
public:
    int no_of_students;
    one() { no_of_students = 0; }
    void new         


        
8条回答
  •  一个人的身影
    2020-11-29 21:26

    You can try this:

    template
    inline const char* getTypeName() {
      return typeid(T).name();
    }
    
    #define DEFINE_TYPE_NAME(type, type_name)  \
      template<>                               \
      inline const char* getTypeName() { \
        return type_name;                      \
      }
    
    DEFINE_TYPE_NAME(int, "int")
    DEFINE_TYPE_NAME(float, "float")
    DEFINE_TYPE_NAME(double, "double")
    DEFINE_TYPE_NAME(std::string, "string")
    DEFINE_TYPE_NAME(bool, "bool")
    DEFINE_TYPE_NAME(uint32_t, "uint")
    DEFINE_TYPE_NAME(uint64_t, "uint")
    // add your custom types' definitions
    

    And call it like that:

    void main() {
     std::cout << getTypeName();
    }
    

提交回复
热议问题