C++ templates

Ace your homework & exams now with Quizwiz!

use either keyword typename or class in "template prefix"

e.g. template <class T>

C++ templates

like "blueprints" for the compiler to use in creating class and function definition

STL

mostly template classes and functions

template definition must be in header file

so compiler can know how to define the functions

MyTemplate <T1> =! MyTemplate <T2>

there is no inheritance or any other kind of formal relationship between the two classes, because compiler defines completely different classes

An alternative to using an inheritance hierarchy

- more flexible, as template classes stand alone - more efficient than using virtual functions

An alternative to function overloading

-but code for concrete types created only as needed -compiler deduces types of user doesn't specify: int x = sizeComp ('a',7) -to specify : x=sizeComp <int,int> ('a',7.5)

Always involve one or more parameterized types

-function template to compare object sizes: template <typename T1, typename T2> int sizeComp (T1 const &o1, T2 const &o2) { return (sizeof o1 - sizeof o2); } -class template for a list that holds any type: template <typename DataType> class List {/* here refer to Data Type objects*/}

sometimes specialized for particular types

-tells compiler to use specialized version instead of creating a new definition template <> char * &greater <char *>(char *s, char*t) -No type concersions though (must be exact match), so usually better to just overload instead of specialize

even a string is actually a specialization of template, defined as follows in namespace std:

-typedef basic_string<char> string; -Also: typedef basic_sting <wchar_t>wstring;


Related study sets

Ch. 15-19 peds, Peds 1 test, Peds Ch. 15, 16, 17, 18, 19

View Set

Culture Anthropology 220 quiz 2 chapter 5

View Set

S-130 Module 7 (Firing Devices) & 8 (Water Use)

View Set

Econ 2301 Chapter 10 Learning Objectives

View Set

Chapter 9, 10, 11: Quiz 3 Review

View Set