I'm trying to build a pointer class with conversion safeguards in it to monitor pointer conversions. Specifically, I want it to do a dynamic_cast inside of an assert and make sure the result is not a nullptr. Unfortunately, if the pointer does not point to a class type, it gives a compile-time error indicating that dynamic_cast cannot be used.
Next I tried:
assert( (std::is_same<T,T2>() || dynamic_cast<T*>(in_ptr)) );
...but this approach still didn't work because short-circuiting only happens at run time; the same error occurred.
My next idea is to build a convert_ok
struct that is specialized such that if both pointers are the same its operator() returns true, but otherwise it returns the bool result of a dynamic_cast.
I think this approach will work, but I feel like I must be missing something from the standard library. std::is_convertable
comes close, but when moving from a base class to a derived class it can only know at run time if the conversion will be legal... hence the dynamic cast.
WHY: Since I know people will ask, I've built a Ptr template that reduces to a regular pointer when NDEBUG is set, but otherwise does reference counting and trips asserts if memory issues occur (reference count goes to 0 without delete, pointer accessed after deletion, pointer deleted multiple times, etc.) It has worked better for me than smart pointers because it does more bookkeeping in debug mode, while having a near-zero overhead when NDEBUG is set. It's already helped me clean up some tricky pointer juggling, and I'm now working to extend its functionality.