11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 27: Tempting C++ Templates 361check the types to make sure that your assumption is correct. Suppose, forexample, you thought that double variables were stored in vv instead of intvalues. The following code would have stored garbage into dValue:double dValue = *(double*)get();The program would certainly go astray; the casts to and from void* defeatthe strong typing built into C++.Tips for Using TemplatesYou should remember a few things when using templates. First, no code is generatedfor a template. (Code is generated after the template is converted into aconcrete class or function.) This implies that a .cpp source file is almost neverassociated with a template class. The entire template class definition, includingall the member functions, is contained in the include file so that it can beavailable for the compiler to expand.Second, a template class does not consume memory. Therefore, there is nopenalty for creating template classes if they are never instanced. On the otherhand, a template class uses memory every time it is instanced. Thus, the codefor Array consumes memory even if Array already exists.Finally, a template class cannot be compiled and checked for errors until itis converted into a real class. Thus, a program that references the templateclass Array might compile even though Array contains obvioussyntax errors. The errors won’t appear until a class such as Array orArray is created.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!