How to order types at compile-time?

前端 未结 3 1199
陌清茗
陌清茗 2020-12-13 20:48

Consider the following program:

#include 
#include 
#include 
#include 

template 

        
3条回答
  •  鱼传尺愫
    2020-12-13 21:45

    This is a slight modification of the method presented by Barry, that works with Visual Studio. Instead of creating compile-time string that stores name of a function:

    template 
    constexpr bool cmp() 
    

    this method directly compares names of two types returned by type_name< T>::name(). Barry's method does not work when names of types T and U returned by macro __PRETTY_FUNCTION__ are separated by comma, since comma may also separate template arguments, when T or U are a class or function templates.

    // length of null-terminated string
    constexpr size_t cstrlen(const char* p) 
    {
        size_t len = 0;
        while (*p) 
        {
            ++len;
            ++p;
        }
    
        return len;
    }
    
    // constexpr string representing type name
    template
    struct type_name
    {
        static constexpr const char* name() 
        { 
            #if defined (_MSC_VER)
                return __FUNCSIG__; 
            #else
                return __PRETTY_FUNCTION__;
            #endif
        };
    };
    
    // comparison of types based on type names
    template
    constexpr bool less()
    {
        const char* A   = type_name::name();
        const char* B   = type_name::name();
    
        size_t a_len    = cstrlen(A);
        size_t b_len    = cstrlen(B);
    
        size_t ab_len   = (a_len < b_len) ? a_len : b_len;
    
        for (size_t i = 0; i < ab_len; ++i) 
        {
            if (A[i] != B[i]) 
                return A[i] < B[i];
        }
    
        return a_len < b_len;
    }
    
    // simple checks
    template
    struct list;
    
    static_assert(less>, list>>());
    static_assert(less>, list, int>>());
    

    This method works on VS. I am not sure if it works on Clang or GCC.

提交回复
热议问题