Compile time type determination in C++

后端 未结 6 1832
囚心锁ツ
囚心锁ツ 2021-02-01 22:26

A coworker recently showed me some code that he found online. It appears to allow compile time determination of whether a type has an \"is a\" relationship with another type. I

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 23:23

    Is there any reason you wouldn't use something like this instead:

    template
    struct IsRelated
    {
        static DerivedT derived();
        static char test(const BaseT&); // sizeof(test()) == sizeof(char)
        static char (&test(...))[2];    // sizeof(test()) == sizeof(char[2])
    
        enum { exists = (sizeof(test(derived())) == sizeof(char)) }; 
    }
    

    ?

    e.g.:

    IsRelated::exists
    

    That way you have access to the information at compile-time.

提交回复
热议问题