Compile time type determination in C++

后端 未结 6 1908
囚心锁ツ
囚心锁ツ 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:01

    It declares two overloaded functions named test, one taking a Base and one taking anything (...), and returning different types.

    It then calls the function with a Derived and checks the size of its return type to see which overload is called. (It actually calls the function with the return value of a function that returns Derived, to avoid using memory)

    Because enums are compile-time constants, all of this is done within the type system at compile-time. Since the functions don't end up getting called at runtime, it doesn't matter that they have no bodies.

提交回复
热议问题