Can I obtain C++ type names in a constexpr way?

前端 未结 2 1927
悲&欢浪女
悲&欢浪女 2020-12-03 01:13

I would like to use the name of a type at compile time. For example, suppose I\'ve written:

constexpr size_t my_strlen(const char* s)
{
        const char* c         


        
2条回答
  •  -上瘾入骨i
    2020-12-03 01:32

    Well, you could, sort of, but probably not quite portable:

    struct string_view
    {
        char const* data;
        std::size_t size;
    };
    
    inline std::ostream& operator<<(std::ostream& o, string_view const& s)
    {
        return o.write(s.data, s.size);
    }
    
    template
    constexpr string_view get_name()
    {
        char const* p = __PRETTY_FUNCTION__;
        while (*p++ != '=');
        for (; *p == ' '; ++p);
        char const* p2 = p;
        int count = 1;
        for (;;++p2)
        {
            switch (*p2)
            {
            case '[':
                ++count;
                break;
            case ']':
                --count;
                if (!count)
                    return {p, std::size_t(p2 - p)};
            }
        }
        return {};
    }
    

    And you can define your desired type_name_length as:

    template 
    constexpr auto type_name_length = get_name().size;
    

    DEMO (works for clang & g++)

提交回复
热议问题