Here is the code : https://ideone.com/plt3Y
template <typename Derived>
class CuriousBase {
};
template <typename T>
class CuriousTemplate : public CuriousBase<CuriousTemplate<T> > {
};
My Question :
**class CuriousTemplate : public CuriousBase<CuriousTemplate<T> > {};** , here is what my confusion lies.
To make object of "CuriousTemplate<T>" , it has to build it's sub-object "CuriousBase<CuriousTemplate<T>>".
To build "CuriousBase<CuriousTemplate<T>>", It has to instantiate "CuriousTemplate<T>" but to instantiate "CuriousTemplate<T>", Again it has build base object "CuriousBase<CuriousTemplate<T>>" and so on ...
Isn't this is infinite inheritance? How this all is working?
Important Q: Am I forgetting some special rule of template instantiation here?
Does this has anything to do with empty base class optimization? , If yes please explain me this too.
Thanks a lot , I really appreciate the help :)
Copyright © 2024 Q2A.MX - All rights reserved.
Answers & Comments
Verified answer
Yes, once T is known, to construct an object of type "CuriousTemplate<T>" , the compiler has to construct its base sub-object of type "CuriousBase<CuriousTemplate<T>>".
Yes, the type name "CuriousTemplate<T>" has to be known before the compiler can come up with the type name for "CuriousBase<CuriousTemplate<T>>".
No, to come up with the type name for "CuriousTemplate<T>" the compiler doesn't need to do anything with any objects. It just needs to know the name of the type T.
Given, for example, T = int, your code resolves to something like
class CuriousBase_CuriousTemplate_int {
};
class CuriousTemplate_int : public CuriousBase_CuriousTemplate_Int {
};
The point of CRTP is that the compiler creates an individual parent type for each derived type, and guarantees that only one type is derived from each parent type (so that static polymorphism can work)