This is already several posts that I sent about this subjet and I apologize if this bothers some of you. After playing around several days and trying different alternatives (patterns) I came up with the following conclusions, which allows me to better formulate my question.
I have a vector of Base * and there are various Derived<T> classes that derive from Base. The different class parameters T are declared at the beginning with a forward declaration. What I need is to take a pair of objects from this vector<Base *> and apply a function(Derived<T1> obj1, Derived<T2> obj2) using templates in order to do some kind of double dispatch. However, I am unable to convert a pointer-to-Base to a pointer-to-Derived when I take an element from the vector. Thus, I cannot use function(Derived<T1> obj1, Derived<T2> obj2).
Of course, this could be simply achieved using dynamic_cast<Derived<T> *>(base_ptr). However, this is not what I want since to do this, one must know T in advance, which is not the case here. I must be able to select whatever elements from the vector, without knowing their Derived<T> type.
Therefore, I tried polymorphic cloning. Although it uses covariant return types, unfortunately, it did not work. The reason, as explained by different people in SO, and according to the C++ standard, is that at compile time, the compiler still does not know the complete type of the object. Thus, although one expects that the clone() should return a Derived<T> *, it returns a Base *.
The few next lines of code express what I mean. In general, the polymorphic cloning is used in the following case:
Base *b1 = new Derived;
Base *b2;
b2 = b1->clone();
This is not what I want. What I need is a pointer-to-Derived:
Base *b1 = new Derived;
Derived *d1;
d1 = b1->clone(); // This is what I want, but it fails.
Here, the compiler complains saying that an object of type Base * cannot be assigned to an object of type Derived *. Hence, I cannot use *d1 in function(,).
I also tried the non-virtual interface (NVI) method, but it did not work.
Does anyone have an idea of how to solve the simple code above, in particular, the last line ? Many thanks in advance.