Template metaprogram converting type to unique number

后端 未结 9 950
小鲜肉
小鲜肉 2020-12-03 03:37

I just started playing with metaprogramming and I am working on different tasks just to explore the domain. One of these was to generate a unique integer and map it to type,

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 04:38

    I think it is possible to do it for a fixed set of types, but quite a bit of work. You'll need to define a specialisation for each type, but it should be possible to use compile-time asserts to check for uniqueness. I'll assume a STATIC_ASSERT(const_expr), like the one in Boost.StaticAssert, that causes a compilation failure if the expression is false.

    Suppose we have a set of types that we want unique IDs for - just 3 for this example:

    class TypeA;
    class TypeB;
    typedef int TypeC;
    

    We'll want a way to compare types:

    template  struct SameType
    {
        const bool value = false;
    };
    
    template  struct SameType
    {
        const bool value = true;
    };
    

    Now, we define an ordering of all the types we want to enumerate:

    template  struct Ordering {};
    
    template <> struct Ordering
    {
        typedef TypeC prev;
        typedef TypeA next;
    };
    
    template <> struct Ordering
    {
        typedef void  prev;
        typedef TypeB next;
    };
    
    template <> struct Ordering
    {
        typedef TypeA prev;
        typedef TypeC next;
    };
    
    template <> struct Ordering
    {
        typedef TypeB prev;
        typedef void  next;
    };
    

    Now we can define the unique ID:

    template  struct TypeInt
    {
        STATIC_ASSERT(SameType::prev::next, T>::value);
        static int value = TypeInt::prev::value + 1;
    };
    
    template <> struct TypeInt
    {
        static int value = 0;
    };
    

    NOTE: I haven't tried compiling any of this. It may need typename adding in a few places, and it may not work at all.

    You can't hope to map all possible types to an integer field, because there are an unbounded number of them: pointer types with arbitrary levels of indirection, array types of arbitrary size and rank, function types with arbitrary numbers of arguments, and so on.

提交回复
热议问题