Skip to content

AnaMac3/42-CPP_Module_07

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 

Repository files navigation

42-CPP_Module_07

42 Common Core CPP Module 07

  • Templates

Table of Contents

Templates

Templates allow you to define the behaviour of a class or function for different data types. A template is a construct that lets the compiler generate a regular class or function at compile time, based on the type argments provided by the user.

Example:

template <typename T>
T minimum(const T& lhs, const T& rhs)
{
    return lhs < rhs ? lsh : rhs;
}

This code defines a template for a functiion that returns a value of type T and takes two parameters of type T.

  • By convention, template parameters are written as single uppercase letters (like T)
  • The keyword typename indicates that the parameter is a placeholder for a type
  • When the function is called, the compiler replaces every instance of T with the actual type specified or deduced
  • The process by which the compiler generates a concrete class or function from a template is called template instantiation. For example, minimun<int> is an instantitation of the template minimum<T>.

Template Classes

  • By convention, the implementations of member functions for templates classes are placed in a separate .tpp file.
  • Each member function must be preceded by template <typename T> to declare that it belongs to a template.
  • When defining methods outside the class, you must write Class<T>::function instead of Class::function, to specify that the function beloong to the template class Class<T>.

Example:

    //MyClass.hpp

    template <typename T>
    class MyClass
    {
        void print(const T& val);
    };

    #include "MyClass.tpp"

    //MyClass.tpp
    template <typename T>
    void MyClass<T>::print(const T& val)
    {
        std::cout << val << std::endl;
    }

More info

w3school - Templates Microsoft Learn - Templates

About

42 Common Core CPP Module 07

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published