I need a way to verify during compile time that upcast/downcast of a pointer to another class (either derived or base) does not change the pointer value. That is, the cast is equivalent to reinterpret_cast.
To be concrete, the scenario is the following: I have a Base class and a Derived class (obviously derived from Base). There is also a template Wrapper class that consists of a pointer to the class specified as a template parameter.
class Base
{
// ...
};
class Derived
:public Base
{
// ...
};
template <class T>
class Wrapper
{
T* m_pObj;
// ...
};
In some situations I have a variable of type Wrapper<Derived>, and I’d like to call a function that receives a (const) reference ro Wrapper<Base>. Obviously there is no automatic cast here, Wrapper<Derived> is not derived from Wrapper<Base>.
void SomeFunc(const Wrapper<Base>&);
Wrapper<Derived> myWrapper;
// ...
SomeFunc(myWrapper); // compilation error here
There are ways to handle this situation within the scope of the standard C++. Like this for example:
Derived* pDerived = myWrapper.Detach();
Wrapper<Base> myBaseWrapper;
myBaseWrapper.Attach(pDerived);
SomeFunc(myBaseWrapper);
myBaseWrapper.Detach();
myWrapper.Attach(pDerived);
But I don’t like this. Not only this demands an awkward syntax, but it also produces an extra code, because Wrapper has a non-trivial d’tor (as you may guessed), and I’m using exception handling. OTOH if the pointer to Base and Derived are the same (like in this example, since there’s no multiple inheritance) – one may just cast myWrapper to the needed type and call SomeFunc, and it will work!
Hence I’ve added the following to Wrapper:
template <class T>
class Wrapper
{
T* m_pObj;
// ...
typedef T WrappedType;
template <class TT>
TT& DownCast()
{
const TT::WrappedType* p = m_pObj; // Ensures GuardType indeed inherits from TT::WrappedType
// The following will crash/fail if the cast between the types is not equivalent to reinterpret_cast
ASSERT(PBYTE((WrappedType*)(1)) == PBYTE((TT::WrappedType*)(WrappedType*)(1)));
return (TT&) *this; // brute-force case
}
template <class TT> operator const Wrapper<TT>& () const
{
return DownCast<Wrapper<TT> >();
}
};
Wrapper<Derived> myWrapper;
// ...
// Now the following compiles and works:
SomeFunc(myWrapper);
The problem is that in some cases the brute-force cast is not valid. For instance in this case:
class Base
{
// ...
};
class Derived
:public AnotherBase
,public Base
{
// ...
};
Here the value of the pointer to Base differs from Derived. Hence Wrapper<Derived> is not equivalent to Wrapper<Base>.
I’d like to detect and prevent attempts of such an invalid downcast. I’ve added the verification (as you may see), but it works in run-time. That is, the code would compile and run, and during the runtime there’ll be a crash (or a failed assertion) in debug build.
This is fine, but I’d like to catch this during compile time and fail the build. A sort of a STATIC_ASSERT.
Is there a way to achieve this?
Short answer: no.
Long answer:
There is limited introspection available at compilation time, and you can for example (using function overload resolution) detects if a class B is an accessible base class of another class D.
However that’s about it.
The Standard does not require full introspection, and notably:
And of course, there is the issue that the object layout is more or less unspecified, anyway (though C++11 adds the ability to distinguish between trivial layout and class with virtual methods if I remember correctly, which helps a bit here!)
Using Clang, and its AST inspection capabilities, I think you could write a dedicated checker, but this seems quite complicated, and is of course totally non-portable.
Therefore, despite your bold claim P.S. Please don’t reply with “why do you want to do this” or “this is against the standard”. I know what what all this for, and I have my reasons to do this., you will have to adapt your ways.
Of course, if we were given a broader picture of your usage of this class, we might be able to pool our brains together and help you figure a better solution.
How to implement a similar system ?
I would propose, first, a simple solution:
Wrapper<T>is the owner class, non-copyable, non-convertibleWrapperRef<U>implements a proxy over an existingWrapper<T>(as long asT*is convertible toU*) and provide the conversions facilities.We will use the fact that all pointers to be manipulated inherit from
UnkDisposable(this is a crucial information!)Code:
Now that we laid down the foundations, we can make our adaptive proxy. Because we will only manipulate everything through
WrapperImpl, we ensure the type-safety (and the meaningful-ness of ourstatic_cast<T*>) by checking conversions throughstd::enable_ifandstd::is_base_ofin the template constructors:It might be tweaked according to your needs, for example you could remove the ability to Copy and Move the
WrapperRefclass to avoid situation where it point to a no longer validWrapper.On the other hand, you could also enrich this using a
shared_ptr/weak_ptrapproach in order to be able to copy and move the wrapper and still guarantee the availability (but beware of memory leaks).Note: it is intentional that
WrapperRefdoes not provide anAttachmethod, such a method cannot be used with a base class. Otherwise with bothAppleandBananaderiving fromFruit, you could attach aBananathrough aWrapperRef<Fruit>even though the originalWrapper<T>was aWrapper<Apple>…Note: this is easy because of the common
UnkDisposablebase class! This is what gives us a common denominator (WrapperImpl).