Create function template with parameter - C++ template

C++ examples for template:template function

Description

Create function template with parameter

Demo Code

#include <iostream>
using namespace std;
template <class T>  // template prefix
T abs(T value)      // header line
{
   T absnum;         // variable declaration
   if (value < 0)
      absnum = -value;//from w w  w .j a va 2 s  . co  m
   else
      absnum = value;
   return absnum;
}
int main(){
      int num1 = -4;
      float num2 = -4.23f;
      double num3 = -4.23456;
      cout << "The absolute value of " << num1 << " is " << abs(num1) << endl;
      cout << "The absolute value of " << num2 << " is " << abs(num2) << endl;
      cout << "The absolute value of " << num3 << " is " << abs(num3) << endl;
      return 0;
}

Result


Related Tutorials