Archived

This forum has been archived. Please start a new discussion on GitHub.

Addition of Handle::staticCast

My suggestion is simple: The smart pointer class used by Ice provides a templated dynamicCast function to up-cast to a smart pointer of a derived object, similarly to up-casting of normal pointer using dynamic_cast in C++. However it provides no staticCast method.

In some cases, when you already known the actual type pointed to you would use static_cast over dynamic_cast in C++ to avoid the overhead associated with the dynamic cast.

The implementation of Handle::staticCast is trivial given the existing implementation of Handle::dynamicCast.

Comments

  • bernard
    bernard Jupiter, FL
    Hi Erik,

    I think a better solution (that you can implement yourself) would be to use a non-member template function such as:
    // Warning: untested code!
    
    namespace IceUtil
    {
    
    template<typename T, typename Y> inline Handle<T>
    staticCast(const HandleBase<Y>& p)
    {
        return Handle<T>(static_cast<T*>(p.get()));
    }
    
    }
    
    

    and then invoke this staticCast with:
      FooPtr x = staticCast<Foo>(bar);
    

    instead of
      FooPtr x = FooPtr::staticCast(bar);
    

    (perhaps you can update the template to get staticCast<FooPtr>(bar))

    We didn't use this syntax in Ice because older C++ compilers don't support well the function<type>(...) syntax.

    Best regards,
    Bernard
  • Hi Bernard,

    I tried out your suggestion, but stumbled upon a little corner of C++ that was unknown to me before... It seems that it is not possible to use static_cast to cast an instance of a base class to an instance of a derived class when you use virtual inheritance instead of normal inheritance (And Ice uses virtual inheritance a lot)...

    So, my original suggestion seems to have a very limited use case.

    Erik