C++ Crash Course: a fast-Paced Introduction


Generic Programming with Templates



Yüklə 7 Mb.
Pdf görüntüsü
səhifə34/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   30   31   32   33   34   35   36   37   ...   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

Generic Programming with Templates
Generic programming is writing code once that works with different types 
rather than having to repeat the same code multiple times by copying and 
pasting each type you want to support. In C++, you use templates to produce 
generic code. Templates are a special kind of parameter that tells the com-
piler to represent a wide range of possible types.
You’ve already used templates: all of the stdlib’s containers use templates. 
For the most part, the type of the objects in these containers doesn’t matter. 
For example, the logic for determining the number of elements in a con-
tainer or returning its first element doesn’t depend on the element’s type.
Suppose you want to write a function that adds three numbers of the 
same type. You want to accept any addable type. In C++, this is a straight-
forward generic programming problem that you can solve directly with 
templates, as Listing 20 illustrates.


An Overture to C Programmers
li
template
T add(T x, T y, T z) { 
u
return x + y + z;
}
int main() {
auto a = add(1, 2, 3); // a is an int
auto b = add(1L, 2L, 3L); // b is a long
auto c = add(1.F, 2.F, 3.F); // c is a float
}
Listing 20: Using templates to create a generic 
add
 function
When you declare 
add
u
, you don’t need to know 
T
. You only need to know 
that all the arguments and the return value are of type 
T
and that 
T
is addable. 
When the compiler encounters 
add
being called, it deduces 
T
and generates a 
bespoke function on your behalf. That’s some serious code reuse!
Class Invariants and Resource Management
Perhaps the single greatest innovation C++ brings to system programming 
is the object life cycle. This concept has its roots in C, where objects have dif-
ferent storage durations depending on how you declare them in your code. 
C++ builds on top of this memory management model with construc-
tors and destructors. These special functions are methods that belong to 
user-defined types. User-defined types are the basic building blocks of C++ 
applications. Think of them as 
struct
objects that can also have functions.
An object’s constructor is called just after its storage duration begins, 
and the destructor is called just before its storage duration ends. Both the 
constructor and destructor are functions with no return type and the same 
name as the enclosing class. To declare a destructor, add a 
~
to the begin-
ning of the class name, as Listing 21 illustrates.
#include
struct Hal {
Hal() : version{ 9000 } { // Constructor 
u
printf("I'm completely operational.\n");
}
~Hal() { // Destructor 
v
printf("Stop, Dave.\n");
}
const int version;
};
Listing 21: A 
Hal
 class containing a constructor and a destructor
The first method in 
Hal
is the constructor 
u
. It sets up the 
Hal
object and 
establishes its class invariants. Invariants are features of a class that don’t 
change once they’ve been constructed. With some help from the compiler 
and the runtime, the programmer decides what the invariants of a class 
are and ensures that their code enforces them. In this case, the constructor 


lii
An Overture to C Programmers
sets the 
version
, which is an invariant, to 
9000
. The destructor is the second 
method 
v
. Whenever 
Hal
is about to be deallocated, it prints 
"Stop, Dave."
to the console. (Getting 
Hal
to sing “Daisy Bell” is left as an exercise to the 
reader.)
The compiler makes sure the constructor and destructor are invoked 
automatically for objects with static, local, and thread local storage dura-
tion. For objects with dynamic storage duration, you use the keywords 
new
and 
delete
to replace 
malloc
and 
free
, Listing 22 illustrates.
#include
struct Hal {

Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   30   31   32   33   34   35   36   37   ...   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin