Template is compiled two times
The book says that the template is compiled two times: Before the instantiation, check the template code itself, this good understanding is to check the template is not related to the code, the second compilation is instantiated in the time to see whether the type into the problem, such as the string is not division.
There is also a problem to be aware of: when the template is instantiated, the compiler will be able to see the definition of the template. The following code hangs because main.cpp contains max.h, but none of the implementations of Max
1 //max.h2Template<typename t>3 Max ... ..4 5 //Max.cpp6#include"max.h"7 .....8 9 //main.cppTen#include"max.h" One A intMain () - { -Max1,2); the ... -}
return type as a parameter
When a compiler instantiates a template, it cannot be inferred from the type of the return value to instantiate.
1 template<typename T1, TypeName t2>2 T1 convert (constinreturn Static_cast<t1> (in);} 3 4 convert<doubleint> (123// good5 Convert (123// noooooo!
Non-template functions are preferred
Hand-made (non-template function) and die-carved (template function) than, hand-made priority.
1#include <iostream>2 3 usingstd::cout;4 usingStd::endl;5 6 intMaxintAintb)7 {8cout <<"int max (int, int) is called."<<Endl;9 returna > B?a:b;Ten } One ATemplate<typename t> -T Max (ConstT & A,ConstT &b) - { thecout <<"template<typename t> t max (const T &, const T &) is called."<<Endl; - returna > B?a:b; - } - + intMain () - { +cout << Max (1,2) << Endl;//non-parametric Max Acout << max<> (1,2) << Endl;//parametric Max at - return 0; -}
Today, this looks like, go to see the mathematical equation.
@2015/6/15
C + + Template programming-chapter II-Function templates