Retrieving a c++ class name programmatically

前端 未结 5 1828
Happy的楠姐
Happy的楠姐 2020-12-04 13:23

I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I\'m aware that none of th

5条回答
  •  生来不讨喜
    2020-12-04 13:29

    What about this,

    Tested on Windows 10 using Visual Studio 2019 (v142).

    #include 
    #include 
    #include 
    
    /**
     @author    blongho
     @fn        template std::string classNameOf()
    
     @brief     Determine the class name of an object
    
     @tparam    Object  Type of the object.
    
     @returns   A name of the class
     @date      2019-09-06
     */
    
    template
    std::string classNameOf() {
        std::string name = typeid(Object).name(); //* user defined types gives "class Type"*\ 
        size_t spacePosition = name.find_first_of(" ");
        if (spacePosition != std::string::npos) {
            return name.substr(spacePosition + 1, name.length());
        }
        return name; // mostly primitive types
    }
    
    
    class Person {
    private:
        /* data */
    public:
        Person() {};
        ~Person() {};
    
    };
    
    class Data
    {
    private:
        /* data */
    public:
        Data() {};
        ~Data() {};
    
    };
    
    struct Type {};
    
    int main() {
        std::cout << "Class name of Person() is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of Data() is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of Type() is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of double is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of std::string is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of int is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of float is \"" << classNameOf() << "\"\n";
        std::cout << "Class name of char is \"" << classNameOf() << "\"\n";
        return 0;
    }
    

    Output

    Class name of Person() is "Person"
    Class name of Data() is "Data"
    Class name of Type() is "Type"
    Class name of double is "double"
    Class name of std::string is "std::basic_string,class std::allocator >"
    Class name of int is "int"
    Class name of float is "float"
    Class name of char is "char"
    

    In Ubuntu 18.04,

    g++ -o test src/main.cpp
    ./test
    Class name of Person() is "6Person"
    Class name of Data() is "4Data"
    Class name of Type() is "4Type"
    Class name of double is "d"
    Class name of std::string is "NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"
    Class name of int is "i"
    Class name of float is "f"
    Class name of char is "c"
    

提交回复
热议问题