Is it possible to implement a class template in such a way that one object could be casted to another if their template arguments are related? Here is an exaple to show the idea (of course it will not compile):
struct Base {};
struct Derived : Base {};
template <typename T> class Foo {
virtual ~Foo() {}
virtual T* some_function() = 0;
};
Foo<Derived>* derived = ...;
Foo<Base>* base = derived;
The additional problem here is that Foo is an abstract class used as an interface containing functions returning T& and T*, so I can't implement a template copy constructor.
I'm writing a universal Iterator class which can hold any STL iterator, and in addition to type erasure I'd like it to be polymorphic, i.e. I could write something like this:
std::list<Derived> l;
MyIterator<Base> it(l.begin());
UPD: That was my mistake, I didn't actually need casting Foo* to Foo* to implement MyIterator, so I think the question is not actual anymore.
The template argument has nothing to do with the content of the object you are pointing to. There is no reason this should work. To illustrate
You will eventually access integer
bar
that doesn't really exist ina
!OK, now that you provided some more information, it's clear you want to do something completely different. Here is some starter:
Then you can use it as
You may want to look into
any_iterator
. With a bit of luck, you can use that template for your purpose (I haven't tested it).