Template metaprogram converting type to unique number

后端 未结 9 963
小鲜肉
小鲜肉 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:23

    This may be doing some "bad things" and probably violates the standard in some subtle ways... but thought I'd share anyway .. maybe some one else can sanitise it into something 100% legal? But it seems to work on my compiler.

    The logic is this .. construct a static member function for each type you're interested in and take its address. Then convert that address to an int. The bits that are a bit suspect are : 1) the function ptr to int conversion. and 2) I'm not sure the standard guarantees that the addresses of the static member functions will all correctly merge for uses in different compilation units.

    typedef void(*fnptr)(void);
    
    union converter
    {
      fnptr f;
      int i;
    };
    
    template
    struct TypeInt
    {
      static void dummy() {}
      static int value() { converter c; c.f = dummy; return c.i; }
    };
    
    int main()
    {
      std::cout<< TypeInt::value() << std::endl;
      std::cout<< TypeInt::value() << std::endl;
      std::cout<< TypeInt< TypeVoidP >::value() << std::endl;
    }
    

提交回复
热议问题