Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

how compiler compile template and type checking?? (c++)

My Question is how compiler compile template and how compiler do type checking.

i wanna know about how compiler compile template code.

first of all, i just show you how i think how template works?

first. compiler copy and paste template code replaced with template argument

template <typename T>
class vector
{
   T* data;
~~~
};

int main()
{
   vector<int> a;
}

--->

class vector<int>
{
   int* data;
~~~
};

int main()
{
   vector<int> a;
}

second. compiler try using this converted code for type checking. ( i think this is why all translation unit using template should have(know) template definition )

this is how i think compiler work. actually i don't know well about how compiler works. i just know only abou preprocessing, linker.....

question from:https://stackoverflow.com/questions/65541368/how-compiler-compile-template-and-type-checking-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Templates are compiled in two phases:

  1. At definition time (no instantiation yet) the template code itself is checked for correctness (ignoring template parameters) for example: syntax errors, unknown names, etc.

  2. At instantiation time the template code is checked again, for ex. all parts that depend on template parameters are checked.

Note: If you just define a template, but don't use it, then only the 1. phase will be checked.

for example in your case:

template <typename T>
class vector
{
   T* data, // 1. Phase check: compile error: missing semicolon
~~~
};

int main()
{
   vector<int> a; // 2. Phase check: Instantiation: T replaced with int and template code rechecked.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...