Reputation: 12941
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?
Upvotes: 4
Views: 1324
Reputation: 300159
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 existing Wrapper<T>
(as long as T*
is convertible to U*
) 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:
namespace details {
struct WrapperDeleter {
void operator()(UnkDisposable* u) { if (u) { u->Release(); } }
};
typedef std::unique_ptr<UnkDisposable, WrapperDeleter> WrapperImpl;
}
template <typename T>
class Wrapper {
public:
Wrapper(): _data() {}
Wrapper(T* t): _data(t) {}
Wrapper(Wrapper&& right): _data() {
using std::swap;
swap(_data, right._data);
}
Wrapper& operator=(Wrapper&& right) {
using std::swap;
swap(_data, right._data);
return *this;
}
T* Get() const { return static_cast<T*>(_data.get()); }
void Attach(T* t) { _data.reset(t); }
void Detach() { _data.release(); }
private:
WrapperImpl _data;
}; // class Wrapper<T>
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 our static_cast<T*>
) by checking conversions through std::enable_if
and std::is_base_of
in the template constructors:
template <typename T>
class WrapperRef {
public:
template <typename U>
WrapperRef(Wrapper<U>& w,
std::enable_if_c< std::is_base_of<T, U> >::value* = 0):
_ref(w._data) {}
// Regular
WrapperRef(WrapperRef&& right): _ref(right._ref) {}
WrapperRef(WrapperRef const& right): _ref(right._ref) {}
WrapperRef& operator=(WrapperRef right) {
using std::swap;
swap(_ref, right._ref);
return *this;
}
// template
template <typename U>
WrapperRef(WrapperRef<U>&& right,
std::enable_if_c< std::is_base_of<T, U> >::value* = 0):
_ref(right._ref) {}
template <typename U>
WrapperRef(WrapperRef<U> const& right,
std::enable_if_c< std::is_base_of<T, U> >::value* = 0):
_ref(right._ref) {}
T* Get() const { return static_cast<T*>(_ref.get()); }
void Detach() { _ref.release(); }
private:
WrapperImpl& _ref;
}; // class WrapperRef<T>
It might be tweaked according to your needs, for example you could remove the ability to Copy and Move the WrapperRef
class to avoid situation where it point to a no longer valid Wrapper
.
On the other hand, you could also enrich this using a shared_ptr
/weak_ptr
approach 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 WrapperRef
does not provide an Attach
method, such a method cannot be used with a base class. Otherwise with both Apple
and Banana
deriving from Fruit
, you could attach a Banana
through a WrapperRef<Fruit>
even though the original Wrapper<T>
was a Wrapper<Apple>
...
Note: this is easy because of the common UnkDisposable
base class! This is what gives us a common denominator (WrapperImpl
).
Upvotes: 8