I\'m trying to cast from one generic to another, say:
myClass anItem = myclass anotherObject;
You can't static cast, as they are incompatible types. You can sometimes create an operator to coerce the type instead
#include
class A { };
class B : public A { };
template
struct holder {
T* value;
holder ( T*value ) : value ( value ) { }
template < typename U > // class T : public U
operator holder () const
{
return holder( value );
}
};
int main ()
{
using namespace std;
B b;
holder hb ( &b );
holder ha = hb;
cout << boolalpha;
cout << ( hb.value == ha.value ) << endl;
return 0;
}
Whether this is a meaningful operation rather depends on the semantic of the template class - if the aFunction
can put anything into the handler, you don't want the more specific object being mutated. Hence you copy somehow, either with a coercion operator or with a template copy constructor and assignment. ( the coercion is less code but might result in more objects being created if you don't use reference parameters )