Skip to content

C++ Notes

Figuring out C++ as I make progress thorugh the DB course (Andy Pavlo)

Templating

A Basic Template function

#include <cstdio>

template <typename T>
T max_value(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int a = max_value(3, 5);         // T is int
    double b = max_value(3.2, 1.8);  // T is double
}
  • based on how the template function max_value is called, the compiler will generate new function definitions during compile time

Check C++insights to understand better

Template class

Same thing for a class as well

#include <iostream>

template <typename T>
class Box {
public:
    T value;
    Box(T val) : value(val) {}
    T get() const { return value; }
};

int main() {
    Box<int> intBox(10);
    Box<std::string> strBox("Hello");
}

Link to explore more

Disable Default Constructor

If we have a class called FancyClass then defining the ctor as FancyClass() = delete; makes sure that the class will never be generated itself