ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2111Templates
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2111

    Object Oriented Programming

    Progress0 / 23 done
    Topics23
    1Introduction to object oriented design2History and advantages of object oriented design3Introduction to object oriented programming concepts4Classes and objects5Data encapsulation6Constructors and destructors7Access modifiers8Const vs non-const functions9Static data members & functions10Function overloading11Operator overloading12Identification of classes and their relationships13Composition and aggregation14Inheritance15Multiple inheritance16Polymorphism17Abstract classes and interfaces18Generic programming concepts19Function & class templates20Standard template library21Object streams22Data and object serialization using object streams23Exception handling
    7 min read
    Topic 19 of 23
    Topic Study Note Illustration
    19

    Function & class templates

    Templates in C++ allow you to write generic code that works with any data type, which promotes reusability and type safety. Templates can be used for both...

    Function and Class Templates in C++

    Templates in C++ allow you to write generic code that works with any data type, which promotes reusability and type safety. Templates can be used for both functions and classes, making them powerful tools in generic programming.


    1. Function Templates

    A function template is a way to define a generic function that can work with any data type. Instead of writing multiple versions of a function for different data types, you can use a single template function that is instantiated with the correct data type when called.

    Syntax of Function Template:

    template <typename T>
    T functionName(T arg1, T arg2) {
        return arg1 + arg2;  // This function works for any type T
    }
    
    • template <typename T>: This defines a placeholder T that can represent any data type.
    • T functionName(T arg1, T arg2): The function will accept two arguments of type T and return a result of type T.

    Example of Function Template:

    #include <iostream>
    using namespace std;
    
    // Function template for addition
    template <typename T>
    T add(T a, T b) {
        return a + b;  // Adds two values of type T
    }
    
    int main() {
        cout << add(5, 3) << endl;          // Works with int
        cout << add(2.5, 3.7) << endl;      // Works with double
        cout << add(1.2f, 2.8f) << endl;    // Works with float
    
        return 0;
    }
    

    Explanation:

    • The add() function is a template that can accept any type T (such as int, double, or float).
    • When add(5, 3) is called, it is instantiated with T = int, and similarly for other data types.

    2. Class Templates

    A class template allows you to define a generic class that can be used with any data type. You can create a single class template that works with multiple data types, eliminating the need to define the same class for different types.

    Syntax of Class Template:

    template <typename T>
    class ClassName {
        T value;  // Member of type T
    
    public:
        ClassName(T val) : value(val) {}  // Constructor
    
        T getValue() {
            return value;  // Getter function
        }
    };
    
    • template <typename T>: Defines the type placeholder T.
    • T value;: A class member that can hold a value of type T.
    • ClassName(T val): A constructor that initializes the value with a parameter of type T.

    Example of Class Template:

    #include <iostream>
    using namespace std;
    
    // Class template to hold a value of type T
    template <typename T>
    class Box {
    private:
        T value;  // Variable of type T
    
    public:
        // Constructor to initialize the value
        Box(T val) : value(val) {}
    
        // Function to get the stored value
        T getValue() {
            return value;
        }
    };
    
    int main() {
        Box<int> intBox(10);           // Box of int
        Box<double> doubleBox(3.14);   // Box of double
        Box<string> stringBox("Hello"); // Box of string
    
        cout << "Integer Box: " << intBox.getValue() << endl;
        cout << "Double Box: " << doubleBox.getValue() << endl;
        cout << "String Box: " << stringBox.getValue() << endl;
    
        return 0;
    }
    

    Explanation:

    • Box is a template class that can hold values of any data type.
    • In main(), we instantiate the Box class for int, double, and string.
    • The getValue() function returns the value stored inside the Box object.

    3. Template Specialization

    Although templates allow for generic programming, there are situations where you might want to define a specific version of a function or class for a particular type. This is where template specialization comes in. Template specialization allows you to define a specific implementation for a given type while keeping the generic version for other types.

    Syntax of Template Specialization:

    template <>
    class ClassName<Type> {
        // Special implementation for Type
    };
    

    Example of Template Specialization for a Class:

    #include <iostream>
    using namespace std;
    
    // Generic class template
    template <typename T>
    class Box {
    private:
        T value;
    
    public:
        Box(T val) : value(val) {}
    
        T getValue() {
            return value;
        }
    };
    
    // Specialization for bool type
    template <>
    class Box<bool> {
    private:
        bool value;
    
    public:
        Box(bool val) : value(val) {}
    
        bool getValue() {
            return value;
        }
    
        void display() {
            cout << (value ? "True" : "False") << endl;
        }
    };
    
    int main() {
        Box<int> intBox(10);
        Box<double> doubleBox(3.14);
        Box<bool> boolBox(true);  // Specialization for bool
    
        cout << "Integer Box: " << intBox.getValue() << endl;
        cout << "Double Box: " << doubleBox.getValue() << endl;
        cout << "Bool Box: ";
        boolBox.display();  // Specialized method for bool type
    
        return 0;
    }
    

    Explanation:

    • The Box<bool> class is specialized to handle the bool type, and it has a display() function to print "True" or "False".
    • The generic version of Box works for types like int and double.

    4. Advantages of Templates

    1. Code Reusability:

      • Templates enable you to write a single piece of code that works for different data types. This reduces the need for repetitive code and increases maintainability.
    2. Type Safety:

      • Templates are type-safe, meaning the compiler checks types at compile time. This prevents runtime errors due to type mismatches.
    3. Efficiency:

      • Templates are expanded at compile time, so there is no runtime overhead for using templates. The code is optimized for the specific data type during compilation.
    4. Flexibility:

      • Templates provide the flexibility to create generic algorithms and data structures that can work with a variety of types. This makes your code more modular and reusable.

    5. Common Use Cases of Templates

    • Standard Template Library (STL):

      • The STL in C++ makes extensive use of templates. It provides generic classes like vector, list, map, and algorithms like sort, find, and accumulate that work with any type.
    • Generic Data Structures:

      • Templates are commonly used to implement data structures like stacks, queues, linked lists, and trees that can store any data type.
    • Mathematical and Scientific Libraries:

      • Templates are often used in libraries that deal with complex numbers, matrices, or mathematical functions where the same operations need to be performed on different data types (like float, double, or int).

    Summary

    1. Function Templates:

      • Used to define generic functions that work with any data type.
      • Instantiated with the specific type when the function is called.
    2. Class Templates:

      • Used to define generic classes that can hold and operate on any type of data.
      • Instantiated with specific types when objects are created.
    3. Template Specialization:

      • Allows you to define specific implementations for particular data types.
    4. Benefits:

      • Code reusability, type safety, and efficiency.

    By leveraging templates, C++ allows for the creation of generic and flexible code that can be reused across multiple types, making your programs more robust and maintainable.

    ← Previous topic 18
    Generic programming concepts
    Next topic 20 →
    Standard template library

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming