👨‍💻
Guide
Laura's GithubSimon's Github
  • What is this gitbook for?
  • 🛠️Useful tools
    • 🏁Header files
    • 🧱C Structures
    • 🔗Linked Lists (todo)
    • 📄Makefiles
    • 🔄Switch statement
    • 🗃️File descriptors (FD)
  • 🖌️MiniLibX
    • MiniLibX Helper Function
    • MiniLibX Hook Examples
  • 0️⃣ Rank 00
    • Libft
      • 📑LIBC functions
        • ft_isalpha
        • ft_isdigit
        • ft_isalnum
        • ft_isascii
        • ft_isprint
        • ft_strlen
        • ft_memset
        • ft_bzero
        • ft_memcpy
        • ft_memmove
        • ft_strlcpy
        • ft_strlcat
        • ft_toupper
        • ft_tolower
        • ft_strchr
        • ft_strrchr
        • ft_strncmp
        • ft_memchr
        • ft_memcmp
        • ft_strnstr
        • ft_atoi
        • ft_calloc
        • ft_strdup
      • 📑Additional functions
        • ft_substr
        • ft_strjoin
        • ft_strtrim
        • ft_split
        • ft_itoa
        • ft_strmapi
        • ft_striteri
        • ft_putchar_fd
        • ft_putstr_fd
        • ft_putendl_fd
        • ft_putnbr_fd
      • 📑Bonus functions
        • ft_lstnew
        • ft_lstadd_front
        • ft_lstsize
        • ft_lstlast
        • ft_lstadd_back
        • ft_lstdelone
        • ft_lstclear
        • ft_lstiter
        • ft_lstmap
  • 1️⃣ Rank 01
    • Born2beRoot
      • 📠What's a virtual machine ?
      • 📠Install your virtual machine
      • 📠P2P Evaluation - Questions
    • ft_printf
      • ▪️Variadic functions
      • ▪️Building the thing
    • get_next_line
      • ▪️open() & read()
      • ▪️Static variables
      • ▪️Building the thing
      • ▪️Commented solution
  • 2️⃣ Rank 02
    • so_long
      • ▪️Understand so_long
      • ▪️Core concepts
      • ▪️Building the thing
    • pipex
      • ▪️Understand pipex
      • ▪️Functions used
      • ▪️Building the thing
    • minitalk
      • ▪️Understand minitalk
      • ▪️Functions used
      • ▪️Building the thing
    • push_swap
      • ▪️Algorithms
      • ◾Building the thing
    • FdF
      • 🗡️Understand FdF
      • 🗡️Graphics programming
      • 🗡️Building the thing
  • 3️⃣ RANK 03
    • Philosophers
      • ▪️Understand Philosophers
      • ▪️Functions used
      • ▪️Building the thing
    • Minishell
      • ▪️Understand Minishell
      • ▪️Functions
      • ◾Building the thing
  • 4️⃣ RANK 04
    • CPP (00 - 04) (doing)
      • CPP00
      • CPP01
      • CPP02
      • CPP03
      • CPP04 (doing)
    • NetPractice
      • Theory
      • Level 1 & 2
    • MiniRT
      • Understand MiniRT
      • Building the thing
  • 5️⃣ RANK 05
    • CPP (05-09) (to-do)
      • CPP05
      • CPP06 (to-do)
      • CPP07
      • CPP08 (to-do)
      • CPP09 (to-do)
    • Inception (doing)
      • 🕓The basics (Docker, Images, etc...)
      • Project Files
    • webserv (to-do)
  • 6️⃣ rank 06
    • ft_transcendence (to-do)
  • 🛂Exams
    • Exam Rank 02
      • Level 1
        • first_word
        • fizz_buzz
        • *ft_putstr
        • *ft_strcpy
        • *ft_strlen
        • ft_swap
        • repeat_alpha
        • rev_print
        • rot_13
        • rotone
        • search_and_replace
        • ulstr
      • Level 2
        • alpha_mirror
        • camel_to_snake
        • do_op
        • *ft_atoi
        • *ft_strcmp
        • ft_strcspn
        • ft_strspn
        • *ft_strdup
        • ft_strpbrk
        • ft_strrev
        • inter
        • last_word
        • ft_is_power_2
        • max
        • print_bits
        • reverse_bits
        • wdmatch
        • swap_bits
        • union
        • snake_to_camel
      • Level 3
        • add_prime_sum
        • epur_str
        • expand_str
        • ft_atoi_base
        • ft_list_size
        • ft_range
        • ft_rrange
        • hidenp
        • lcm
        • paramsum
        • pgcd
        • print_hex
        • rstr_capitalizer
        • str_capitalizer
        • tab_mult
      • Level 4
        • flood_fil
        • fprime
        • ft_split
        • ft_itoa
        • ft_list_foreach
        • ft_list_remove
        • rev_wstr
        • rotstring
        • sort_int_tab
        • sort_list
    • Exam Rank 03
    • Exam Rank 04
    • Exam Rank 05
      • Module 0
  • 👥Team
Powered by GitBook
On this page
  • Main topics
  • Templates
  • Class templates

Was this helpful?

  1. 5️⃣ RANK 05
  2. CPP (05-09) (to-do)

CPP07

PreviousCPP06 (to-do)NextCPP08 (to-do)

Last updated 1 year ago

Was this helpful?

Main topics

C++ templates

I think it was the simplest CPP module to understand... It really is an intuitive concept that will save you a lot of time in your future projects! Let's directly dive into this topic

Templates

Templates in C++ allow you to write generic code that can work with different data types without duplicating code. Let's use a super simple example:

Imagine you want to create a function that swaps two values.

Without templates, you might create a separate function for each data type you want to swap, like this:

void swapIntegers(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

void swapDoubles(double& a, double& b) {
    double temp = a;
    a = b;
    b = temp;
}

With templates, you can create a single function that works with various data types:

template <typename T>
void swapValues(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}
  • template <typename T>: This line declares a template with a placeholder type T. It tells the compiler that we'll use T to represent different data types.

  • void swapValues(T& a, T& b): This is the generic function that can swap values of any data type represented by T. It takes two references as parameters (to modify the original values) and uses T for the temporary variable.

Now, you can use swapValues for integers, doubles, or any other data type without writing separate swap functions for each type:

int main() 
{
    int x = 5, y = 10;
    double a = 2.5, b = 7.3;

    swapValues(x, y);  // Swaps integers
    swapValues(a, b);  // Swaps doubles

    return 0;
}

And...that's it, basically. You'll also need to implement class templates :

Class templates

Class templates in C++ are a way to create generic classes that can work with different data types or objects. They are similar in concept to function templates, but instead of creating generic functions, you create generic classes.

Suppose you want to create a generic container class called Box that can hold different types of objects. You can use a class template to achieve this:

template <typename T>
class Box {
private:
    T content;

public:
    Box(const T& item) : content(item) {}

    T getItem() const {
        return content;
    }
};
  • template <typename T>: This line declares a class template with a placeholder type T. It tells the compiler that T will represent different data types or object types.

  • class Box: This is the declaration of the generic class named Box (a classical declaration - what you did in the other modules basically)

  • T content;: This is a member variable of type T, which represents the content that the Box can hold.

  • Box(const T& item) : content(item) {}: This is a constructor that takes an object of type T as a parameter and initializes the content member with that object.

  • T getItem() const { return content; }: This is a member function that retrieves the content of the Box.

Now, you can use the Box class template to create instances for different types:

main() {
    Box<int> intBox(42);            // A Box that holds an integer
    Box<double> doubleBox(3.14);    // A Box that holds a double
    Box<std::string> stringBox("Hello, World!"); // A Box that holds a string

    int intValue = intBox.getItem();
    double doubleValue = doubleBox.getItem();
    std::string stringValue = stringBox.getItem();

    return 0;
}

Class templates are especially useful when you want to create reusable and type-safe container classes or data structures.

Anyway. Templates aren't a difficult concept to understand, and you'll soon get the hang of it ! But make sure you understand them, because we're going to need them for module 8, which deals with containers... see you there!

😄