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
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Generic Programming Concepts
    Object Oriented ProgrammingTopic 19 of 24

    Generic Programming Concepts

    7 minread
    1,203words
    Intermediatelevel

    Generic Programming Concepts in C++

    Generic programming is a programming paradigm that aims to make code more flexible, reusable, and type-agnostic. It focuses on writing algorithms and data structures that can work with any data type. In C++, generic programming is primarily achieved using templates. Templates allow functions, classes, and structs to operate with generic types without specifying the exact data types upfront.

    Key Concepts of Generic Programming

    1. Templates in C++:

      • Templates are the core of generic programming in C++. A template is a blueprint or a prototype for creating a function, class, or object, allowing for parameterized types.
      • Templates can be used to write functions or classes that can work with any data type without needing to specify the type at the time of writing the code.
    2. Function Templates:

      • A function template allows a single function to operate on different data types. Instead of defining multiple versions of the same function for each data type, you can define a generic version using a template.

      Syntax of Function Template:

      template <typename T>
      T add(T a, T b) {
          return a + b;
      }
      

      In this example, the function add can add values of any type (e.g., int, double, etc.), and the exact type is determined at compile-time when the function is called.

      Example:

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

      Output:

      7
      8
      3.5
      
    3. Class Templates:

      • Class templates allow you to create classes that can handle any data type. You define the class structure with placeholder data types and specify the actual types when creating objects of the class.

      Syntax of Class Template:

      template <typename T>
      class Box {
      private:
          T value;
      public:
          Box(T v) : value(v) {}
          T getValue() {
              return value;
          }
      };
      

      Example:

      #include <iostream>
      using namespace std;
      
      template <typename T>
      class Box {
      private:
          T value;
      public:
          Box(T v) : value(v) {}
          T getValue() {
              return value;
          }
      };
      
      int main() {
          Box<int> box1(5);
          Box<double> box2(3.14);
      
          cout << "Box1 contains: " << box1.getValue() << endl;
          cout << "Box2 contains: " << box2.getValue() << endl;
      
          return 0;
      }
      

      Output:

      Box1 contains: 5
      Box2 contains: 3.14
      
    4. Template Specialization:

      • Template specialization allows you to provide a specific implementation of a template for a certain type or set of types.
      • If you need to handle a specific type differently, you can specialize the template for that type.

      Syntax of Template Specialization:

      template <typename T>
      void print(T value) {
          cout << "Generic print: " << value << endl;
      }
      
      // Specialization for int
      template <>
      void print<int>(int value) {
          cout << "Specialized print for int: " << value << endl;
      }
      

      Example:

      #include <iostream>
      using namespace std;
      
      template <typename T>
      void print(T value) {
          cout << "Generic print: " << value << endl;
      }
      
      template <>
      void print<int>(int value) {
          cout << "Specialized print for int: " << value << endl;
      }
      
      int main() {
          print(3.14);  // Calls generic print
          print(5);     // Calls specialized print for int
      
          return 0;
      }
      

      Output:

      Generic print: 3.14
      Specialized print for int: 5
      
    5. Template Parameters:

      • Templates can have different types of parameters:
        • Type Parameters (typename or class): Used to specify the type for the template.
        • Non-type Parameters: Used to specify constants, such as integers or pointers, that will be used during compilation.

      Example with Non-type Parameters:

      template <typename T, int size>
      class Array {
      private:
          T arr[size];
      public:
          void setElement(int index, T value) {
              if (index < size) arr[index] = value;
          }
          T getElement(int index) {
              if (index < size) return arr[index];
              return T();  // Return default value if out of bounds
          }
      };
      
      int main() {
          Array<int, 5> arr;
          arr.setElement(0, 10);
          arr.setElement(1, 20);
          cout << arr.getElement(0) << endl;  // 10
          cout << arr.getElement(1) << endl;  // 20
      
          return 0;
      }
      
    6. Variadic Templates:

      • C++11 introduced variadic templates, allowing you to pass a variable number of arguments to templates. This makes the templates more flexible and powerful.

      Example with Variadic Templates:

      template <typename... Args>
      void print(Args... args) {
          (cout << ... << args) << endl;  // Fold expression (C++17 feature)
      }
      
      int main() {
          print(1, 2.5, "Hello", 'A');  // Can print any number and type of arguments
          return 0;
      }
      

      Output:

      12.5HelloA
      

    Advantages of Generic Programming

    1. Code Reusability:

      • By writing generic functions and classes, you can reuse the same code with different data types. This reduces the need for code duplication.
    2. Type Safety:

      • Templates provide type safety because the types are checked at compile time. You don’t have to worry about passing incorrect types to functions.
    3. Efficiency:

      • Since template code is resolved at compile time, there is no performance overhead compared to using object-oriented polymorphism or virtual functions.
    4. Extensibility:

      • It’s easy to extend generic code to handle new data types by simply instantiating the template with the desired type.
    5. Abstraction:

      • Generic programming allows for high-level abstractions where the actual data types are abstracted away, which can make code more general and versatile.

    Disadvantages of Generic Programming

    1. Code Bloat:

      • Template code is instantiated separately for each type, leading to a potential increase in binary size. This is known as code bloat, as separate versions of the template code are generated for each distinct type used.
    2. Compilation Time:

      • Template-heavy code can significantly increase compilation time due to the need to generate code for each template instantiation.
    3. Error Messages:

      • Template errors are often more difficult to debug because the error messages can be very complex, especially for templates with non-type parameters or variadic templates.
    4. Complexity:

      • While templates can be powerful, they can also make the code harder to understand, especially for developers unfamiliar with the paradigm.

    Summary

    • Generic programming is a technique that allows functions and classes to operate on any data type.
    • Templates are the primary tool for implementing generic programming in C++, enabling the definition of type-agnostic functions and classes.
    • Function templates and class templates allow you to write generic code that works for any data type.
    • Template specialization allows you to define specific implementations for certain types.
    • Variadic templates and non-type parameters further extend the flexibility of templates.
    • Advantages include code reusability, type safety, and efficiency, while disadvantages include code bloat, longer compilation times, and complex error messages.
    Previous topic 18
    Interfaces
    Next topic 20
    Function 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,203
      Code examples0
      DifficultyIntermediate