I have a C++03 application with a class that holds a single instance of a type where I am trying to convert between a holder of a derived type to a holder of a base type. For example:
class B { public: virtual ~B() { }; };
class A : public B { };
template< typename T >
class Container
{
public:
explicit Container( T* obj ) : obj_( obj ) { };
Container( const Container< T >& ref ) : obj_( ref.obj_ ) { };
template< typename U > operator Container< U >() {
return Container< U >( obj_ );
};
private:
T* obj_;
};
This works fine:
int main()
{
Container< A > a_ref( new A() );
Container< B > b_ref = a_ref;
return 0;
}
This gives me the error invalid initialization of reference of type ‘Container<B>&’ from expression of type ‘Container<A>’:
void Foo( Container< B >& cb ) { }
int main()
{
Container< A > a_ref( new A() );
Foo( a_ref );
return 0;
}
This gives me the error error: invalid initialization of non-const reference of type ‘Container<B>&’ from a temporary of type ‘Container<B>’L
int main()
{
Container< A > a_ref( new A() );
Foo( static_cast< Container< B > >( a_ref ) );
return 0;
}
How can I pass a Container< A > type to a function that expects a Container< B > type? Do I need to make a copy of the object first?
Container<A>andContainer<B>are totally different class.You can have something like
container_cast<T>(U)that converts aContainer<A>toContainer<B>container_cast will construct another
Container<T>by taking theobj_Container<U>and casting thatobj_toT*