Templates in C++

 Templates in C++


Templates are a feature of C++ that allow for generic programming. They allow you to define a function or class that can work with any type of data, without needing to write separate code for each data type. Here's an example of a simple function template in C++:


c++


#include <iostream>


template<typename T>

T add(T a, T b) {

  return a + b;

}


int main() {

  int a = 3, b = 4;

  double x = 1.5, y = 2.5;


  std::cout << "Integers added: " << add(a, b) << std::endl;

  std::cout << "Doubles added: " << add(x, y) << std::endl;


  return 0;

}

In this example, we've defined a function template add that takes two arguments of any type T and returns their sum. In the main function, we call the add function twice, once with int arguments and once with double arguments, and print out the results.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...