ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    COMP2111
    Progress0 / 23 topics
    Topics
    1. Introduction to object oriented design2. History and advantages of object oriented design3. Introduction to object oriented programming concepts4. Classes and objects5. Data encapsulation6. Constructors and destructors7. Access modifiers8. Const vs non-const functions9. Static data members & functions10. Function overloading11. Operator overloading12. Identification of classes and their relationships13. Composition and aggregation14. Inheritance15. Multiple inheritance16. Polymorphism17. Abstract classes and interfaces18. Generic programming concepts19. Function & class templates20. Standard template library21. Object streams22. Data and object serialization using object streams23. Exception handling
    COMP2111›Generic programming concepts
    Object Oriented ProgrammingTopic 18 of 23

    Generic programming concepts

    7 minread
    1,262words
    Intermediatelevel

    Generic Programming Concepts in C++

    Generic programming is a programming paradigm that focuses on writing code that works with any data type. The goal of generic programming is to create functions and data structures that can operate on different types of data without being rewritten for each specific type. This is mainly achieved using templates in C++.

    In C++, templates are used to define functions, classes, and algorithms that can work with any data type, and they are central to the concept of generic programming.


    1. Templates in C++

    Templates allow you to define functions or classes that can operate with any data type. They provide the flexibility to work with multiple data types without the need to duplicate code for each type. Templates are the foundation of generic programming in C++.

    Types of Templates:

    1. Function Templates
    2. Class Templates

    2. Function Templates

    A function template is a template that defines a generic function. This function can then be used with different data types. The function template is instantiated (created) when you call it with a specific data type.

    Syntax of Function Template:

    template <typename T>  // or template <class T>
    T add(T a, T b) {
        return a + b;
    }
    
    • T is a placeholder for any data type, which will be replaced with an actual type when the function is called.

    Example of Function Template:

    #include <iostream>
    using namespace std;
    
    template <typename T>
    T add(T a, T b) {
        return a + b;
    }
    
    int main() {
        cout << add(10, 20) << endl;        // Works with int
        cout << add(3.5, 4.5) << endl;      // Works with double
        cout << add(1.2f, 2.3f) << endl;    // Works with float
    
        return 0;
    }
    

    Explanation:

    • The add() function is a template that can take arguments of any type T and return the sum of the two values.
    • The function is instantiated for different types like int, double, and float when called.

    3. Class Templates

    A class template allows you to define a generic class. Like function templates, class templates are also parameterized by types, and you can create objects of different types based on the template.

    Syntax of Class Template:

    template <typename T>  // or template <class T>
    class Box {
    private:
        T value;
    public:
        Box(T val) : value(val) {}
        T getValue() {
            return value;
        }
    };
    
    • The T is a placeholder for any data type, which is defined when the object is created.

    Example of Class Template:

    #include <iostream>
    using namespace std;
    
    template <typename T>
    class Box {
    private:
        T value;
    public:
        Box(T val) : value(val) {}
        T getValue() {
            return value;
        }
    };
    
    int main() {
        Box<int> intBox(10);       // Box of int
        Box<double> doubleBox(3.14);  // Box of double
    
        cout << "Integer Box: " << intBox.getValue() << endl;
        cout << "Double Box: " << doubleBox.getValue() << endl;
    
        return 0;
    }
    

    Explanation:

    • The Box class template is created for a specific type (int, double, etc.) when instantiated.
    • The Box<int> is a class that stores an int, and Box<double> stores a double.

    4. Template Specialization

    While templates allow for generic programming, there are cases where you may want to write specific code for a particular data type. Template specialization allows you to define a custom implementation of a template for a specific type.

    Syntax of Template Specialization:

    template <>
    class Box<bool> {
    private:
        bool value;
    public:
        Box(bool val) : value(val) {}
        bool getValue() {
            return value;
        }
    };
    

    Example of Template Specialization:

    #include <iostream>
    using namespace std;
    
    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;
        }
    };
    
    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.getValue() << endl;
    
        return 0;
    }
    

    Explanation:

    • A specific implementation of the Box class template is provided for the bool data type.
    • When Box<bool> is instantiated, the specialized version of the Box class is used, while other types use the generic version.

    5. Variadic Templates

    C++11 introduced variadic templates, which allow templates to accept a variable number of template arguments. This is particularly useful when you don't know in advance how many arguments you will be dealing with.

    Syntax of Variadic Templates:

    template <typename... Args>
    void print(Args... args) {
        (cout << ... << args) << endl;  // Fold expression (C++17)
    }
    
    • Args... is a parameter pack that can accept any number of arguments.

    Example of Variadic Template:

    #include <iostream>
    using namespace std;
    
    template <typename... Args>
    void print(Args... args) {
        (cout << ... << args) << endl;  // Fold expression to print all arguments
    }
    
    int main() {
        print(10, 20, 30);        // Works with multiple ints
        print(1.1, 2.2, 3.3);     // Works with multiple doubles
        print("Hello", "World");  // Works with multiple strings
    
        return 0;
    }
    

    Explanation:

    • The print() function is a variadic template that can accept any number of arguments of different types.
    • The fold expression (cout << ... << args) simplifies printing all arguments.

    6. Advantages of Generic Programming

    1. Code Reusability:

      • Templates allow you to write general algorithms and data structures that work with any type of data, reducing the need for duplicated code.
    2. Type Safety:

      • Since templates are type-checked at compile time, you can catch errors early. There is no need for casting, and type mismatches can be avoided.
    3. Efficiency:

      • Templates are resolved at compile time, meaning no runtime overhead for type checking or conversion.
    4. Extensibility:

      • Generic programming makes it easy to extend the functionality of a program. You can write code that works with new types without modifying existing code.

    7. Examples of Generic Programming in C++

    1. Standard Template Library (STL):

      • The STL is a library that makes extensive use of templates. It provides generic implementations for containers (like vector, list, and map) and algorithms (like sort, find, and copy).
    2. Algorithms:

      • Many algorithms in C++ (like sorting, searching, and manipulating data) are implemented as template functions to work with any type of data.

    Summary of Generic Programming Concepts:

    • Generic programming focuses on writing algorithms and data structures that can work with any data type.
    • In C++, templates allow you to create generic functions and generic classes.
    • Function templates and class templates provide the flexibility to write reusable code without specifying the data type in advance.
    • Template specialization allows you to define specific behavior for particular types.
    • Variadic templates allow functions to accept a variable number of arguments, making your code even more flexible.

    Overall, generic programming helps you write more flexible, reusable, and type-safe code in C++, promoting efficiency and reducing redundancy.

    Previous topic 17
    Abstract classes and interfaces
    Next topic 19
    Function & class templates

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,262
      Code examples0
      DifficultyIntermediate