C++: Can virtual inheritance be detected at compile time?

后端 未结 8 428
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 10:55

I would like to determine at compile time if a pointer to Derived can be cast from a pointer to Base without dynamic_cast<>. Is this possible using templates and metaprogramm

8条回答
  •  日久生厌
    2021-02-02 11:48

    This may be a little naive (I'm much stronger in C than I am in C++) so I might not understand what you're trying to do, but if it's casting pointers you're talking about, C-style casts work perfectly well (eg. (D *)foo), or the C++ equivalent reinterpret_cast. That being said, this can be very dangerous, because you don't have any runtime checking, and thus need to be sure that you're casting into the correct type. Then again, if you wanted to have an easy way to check whether this is a correct assumption or not, we are back to square one. However, it appears you are trying to compare pointers above, which are all the same (they are basically integers). As far as I know, there is no way to determine an object's class at runtime in C++, including sizeof, which works at compile time. Basically, there's no way to do what you want to do (at least not with standard C++), however the actual cast wont cause any issues, just using the newly cast pointer in improper ways. If you absolutely need this functionality, you would probably be best to include a virtual function in your base class that reports what class it is (preferably with an enum value), and overload it in whichever subclass you hope to determine whether you can cast too.

提交回复
热议问题