As you can see, both are templated, and inside of the Base class function I need to create an instance of Derived. Of course, the way it is now I'm getting an error Derived does not name a type. Unfortunately though, I can't just forward-declare Derived, because it will lead to another error variable 'Derived d ' has initializer but incomplete type.

From the SO question I mentioned above I understand that the compiler needs to know about all the template parameters to be able to forward-declare it correctly. But obviousle I can't just move Derived declaration up, because it will lead to exactly same problem, just vice-versa.

Does this have anything to do with templates?
–
juanchopanzaSep 28 '12 at 5:58

2

I would argue it's Derived that should have fromBase.
–
GManNickGSep 28 '12 at 5:59

a. you are missing ; after the class definitions. b. I agree with GManNickG - what you did is not good OOP.
–
elyashivSep 28 '12 at 6:02

@elyashiv, thx, I accidentally removed them while making the example ;)
–
SingerOfTheFallSep 28 '12 at 6:03

@GManNickG, that's a good point, I'll consider it ;) But anyway, I would like to know if it's possible the way I put it, even for the purpose of learning if it's fundamentally possible...
–
SingerOfTheFallSep 28 '12 at 6:05

3 Answers
3

// Declare, but do not define
class Derived;
class Base {
public:
// Declare, but do not define
// at this point Derived must be declared to be able
// to use it in the return type
Derived toDerived();
};
// Define
class Derived: public Base {
// Rest of definition
};
// At this point Derived is defined
// Define
Derived Base::toDerived()
{
// Implementation goes here
}

This problem has nothing with templates. You could just use forward declaration of Derived to compile declaration of Base::toDerived() and move the function definition
depending on DerivedafterDerived definition:

If this is all in a header, it needs the inline keyword in front of the definition of Base::toDerived to avoid linker errors.
–
Mark LakataMay 21 at 18:51

@MarkLakata: Well I would rather place the inline in front of the declaration in the class. Then it tells the reader that at definition follows later on in the header. That said, nothing indicated that this was a header, and in answers it's best to not add stuff that's not strictly necessary (it can easily be added when desired, but it's more difficult to decide that removing it is safe).
–
Cheers and hth. - AlfMay 21 at 22:22