There are a number of ways to implement smart pointer casting, each with a slightly different syntax and ease of use/clutter. As far as I know there's no generic way to implement casting from a base class to derived class so direct assignment becomes possible as an automatic feature. If anyone has further insight into this, I'd appreciate it.
Currently, I've opted to implement casting via a separate custom function, not operator, which calls the constructor for a new pointer while retaining all allocated memory pointers (note that the A parameter is related to my memory manager):
template<class T>
ISharedPtr {
...
//the cast function
template<typename CastType>
ISharedPtr<CastType> Cast() { return ISharedPtr<CastType>((CastType*)ptr, iRefCount, iSize, (ISharedPtr<CastType>*)A); }
};
//casting now becomes:
ISharedPtr<IBase> base;
ISharedPtr<IDerived> = base.Cast<IDerived>();
To me this syntax is concise and to the point. Nevertheless, it's cumbersome and looks unintuitive due to the trailing nature of the cast. The word cast itself implies putting something into something,eg int(10.f), not taking something out of something.
How would/did you implement this and if you have any further thoughts on the topic, do share!






