fork download
  1. // http://stackoverflow.com/questions/31878000/static-assertion-that-a-base-pointer-equals-a-derived-pointer
  2.  
  3. template<typename D, typename B>
  4. struct CheckCasting {
  5. static D d_static;
  6.  
  7. constexpr
  8. static B* bp = &d_static; // the original object is D,
  9. // that allows us to static_cast both ways
  10.  
  11. static
  12. constexpr bool static_equals_reinterpret() {
  13. return static_cast<void*>(static_cast<D*>(bp))
  14. == static_cast<void*>( bp );
  15. }
  16. };
  17.  
  18. struct Base {
  19. constexpr Base() : i(0) {}
  20. int i;
  21. };
  22.  
  23. struct derived_with_virtual : public Base {
  24. derived_with_virtual() {}
  25. virtual void foo() { }
  26. };
  27. struct without_virtual : public Base {
  28. without_virtual() {}
  29. };
  30.  
  31. static_assert( ! CheckCasting<derived_with_virtual, Base> :: static_equals_reinterpret() ,"");
  32. static_assert( CheckCasting<without_virtual , Base> :: static_equals_reinterpret() ,"");
  33.  
  34. int main() {
  35. }
  36.  
Success #stdin #stdout 0s 3452KB
stdin
Standard input is empty
stdout
Standard output is empty