Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

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

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* cp = s;
        while(*cp != '') { cp++; };
        return cp - s;
}

and now I want to have:

template <typename T>
constexpr auto type_name_length = my_strlen(typeid(T).name());

But alas, typeid(T).name() is just const char*, not constexpr... is there some other, constexpr way to get a type's name?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<class T>
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 <typename T>
constexpr auto type_name_length = get_name<T>().size;

DEMO (works for clang & g++)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...