Files
ooplab/lab8/file.org
Amneesh Singh 4824ab9855 labs 8: init
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2022-12-26 17:30:37 +05:30

1.6 KiB

Write a program to define the function template for swapping two items of the various data types such as integer ,float,and characters.

#include <iostream>

template <typename T, std::enable_if_t<std::is_arithmetic<T>::value, T> = 0>
void swap(T &x, T &y) {
  x += y;
  y = x - y;
  x -= y;
}

int main() {
  char x = '[';
  char y = 'w';

  swap(x, y);

  std::cout << "x = " << x << ", y = " << y;

  return 0;
}

Write a program to define the function template for calculating the square of given numbers with different data types.

#include <iostream>

template <typename T>
std::enable_if_t<std::is_arithmetic<T>::value, T> sq(T x) {
  return x * x;
}

int main() {
  float x = 4.4;

  std::cout << "double: " << sq((double)5.3) << "\nlong: " << sq(4l);

  return 0;
}

Write a program to illustrate how template functions can be overloaded.

#include <iostream>

template <typename T>
std::enable_if_t<std::is_integral<T>::value, T> fn(T x) {
  return x * x;
}

template <typename T>
std::enable_if_t<std::is_floating_point<T>::value, T> fn(T x) {
  return --x;
}

int main() {
  float x = 4.4;

  std::cout << "floating: " << fn((double)5.3) << "\nintegral: " << fn(4l);

  return 0;
}