C++ Get name of type in template

后端 未结 10 2123
天涯浪人
天涯浪人 2020-11-27 11:28

I\'m writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, whic

10条回答
  •  Happy的楠姐
    2020-11-27 11:57

    typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

    This piece of code will return you the appropriate type

    #define DECLARE_SET_FORMAT_FOR(type) \
        if ( typeid(type) == typeid(T) ) \
            formatStr = #type;
    
    template
    static std::string GetFormatName()
    {
        std::string formatStr;
    
        DECLARE_SET_FORMAT_FOR( uint8_t ) 
        DECLARE_SET_FORMAT_FOR( int8_t ) 
    
        DECLARE_SET_FORMAT_FOR( uint16_t )
        DECLARE_SET_FORMAT_FOR( int16_t )
    
        DECLARE_SET_FORMAT_FOR( uint32_t )
        DECLARE_SET_FORMAT_FOR( int32_t )
    
        DECLARE_SET_FORMAT_FOR( float )
    
        // .. to be exptended with other standard types you want to be displayed smartly
    
        if ( formatStr.empty() )
        {
            assert( false );
            formatStr = typeid(T).name();
        }
    
        return formatStr;
    }
    

提交回复
热议问题