Chapters 7 & 8
Strictly enforces valid types and operations
Type rules are enforced at compile time
#include <iostream>
#include <cstring>
template <typename Type>
Type get_min(Type a, Type b) {
return a < b ? a : b;
}
template <>
const char* get_min<const char*>(const char* a, const char* b) {
return std::strcmp(a, b) < 0 ? a : b;
}
int main() {
std::cout << get_min(2, 1) << std::endl;
std::cout << get_min("hello", "world") << std::endl;
}null is one option, but it can be used differently in
different contextsType Option represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Rust code
Introduced in Pascal:
Also introduced in Pascal:
. notation.On most systems, the layout of items in a struct can change the storage space requirements due to alignment constraints.
Have you ever needed to write code to remove duplicate elements from a list?
The difference between a bad programmer and a good one is whether they consider their code or their data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.
- Linus Torvalds
void in C, Object in
Java, and object in C#Let’s revisit our previous C container example to use void.
#include <stdio.h>
typedef struct {
int inner;
} ContainerA;
typedef struct {
int inner;
} ContainerB;
// Use void to accept any pointer
void increment(void* container) {
// Cast pointer to ContainerB type
((ContainerB*)container)->inner += 1;
}
int main() {
ContainerA container = {0};
increment(&container);
printf("Number %d\n", container.inner);
}C++ provides the auto keyword to infer types
Some languages are statically typed while providing type inference such that explicit types are rarely required. Examples are ML, Haskell, and Rust.
fn main() {
let elem = 5u8;
// The compiler knows that `elem` has type u8
let mut vec = Vec::new();
// The compiler doesn't yet know the exact type of `vec`
// It just knows that it's a vector (`Vec<_>`)
vec.push(elem);
// Aha! Now the compiler knows that
// `vec` is a vector of `u8`s (`Vec<u8>`)
println!("{:?}", vec);
}#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(void) {
char * a = malloc(6);
char * b = malloc(4);
strcpy(a, "Alice");
strcpy(b, "Bob");
// Shallow compare
printf("%d\n", a == b); // False
printf("%d\n", a == a); // True
// Undefined behavior, typical results provided
printf("%d\n", a == "Alice"); // False
printf("%d\n", a != "Bob"); // True
// Deep compare
printf("%d\n", strcmp(a, a) == 0); // True
printf("%d\n", strcmp(a, b) == 0); // False
printf("%d\n", strcmp(a, "Alice") == 0); // True
}