Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template code order parsing/CRTP

Can someone give a hint how does compiler process expressions such as

class DerivedA: public ParentTemplateClass<DerivedA>{
}

For mee it looks like:

this boy's father is a "son" of this boy

I mean it's not obvious for me how "parsing" of the class DerivedA can be completed WITHOUT knowing the exactly "description" of parent class. Seems' it can not. So parent class must be processed before children, but in such situation parent depends on children..and I'm stuck there.

Yeah there some articles on the web which describe usage of such thing, e.g. an article about Curiously Recurring Template Pattern ( http://en.wikibooks.org/wiki/More_C++_Idioms/Curiously_Recurring_Template_Pattern) but that's not some kind of standart or smth near. There must be clear behaviour description such as operations ordering isn't it?

ANSWERED: Thnx to everyone. Yeah forward decl analogy seems legit for me to stop damaging my brain. Templates are still state of art for me cause of its hidden sublanguage nature and i cant just g++ -E :)

like image 754
sohel Avatar asked Sep 11 '12 12:09

sohel


2 Answers

After your code says class DerivedA, the symbol DerviedA is declared. At the point it can be used as a template parameter. C++ compilers do several passes on the code, so at that point in parsing the compiler will "believe" that your intention was correct and that it will eventually get the definition of that class (when it is about to instantiate the template, i.e. you actually use that type). If not, it will complain at that point. A similar thing happens if you used a forward declared class in a declaration but didn't provide a definition before using it.

like image 83
Tamás Szelei Avatar answered Sep 22 '22 01:09

Tamás Szelei


At the point at which the template is instantiated, DerivedA is incomplete; it has been declared, but not fully defined. Incomplete types can be used in various ways - for example, you can declare pointers or references to them, declare functions with them as return or parameter types, and a few other things. You can't create objects, inherit from them, access their members, or in general do anything that requires more information than just the class name.

As long as the class template only does these things, there is no problem.

like image 36
Mike Seymour Avatar answered Sep 22 '22 01:09

Mike Seymour