std::cout << "Enter decimal number: " ; std::cin >> input ; std::cout << "0x" << std::hex << input << '\n' ;
if adding an input, which can be boolean or float or int, will be passed back in the internal function call ...
Using function templates based on argument types, C generates separate functions to properly manage each type of call. All definitions of function templates begin with a keyword template, followed by arguments enclosed in angle brackets <and>. For the type of data to be tested, one formal parameter T is used.
Consider the following program, in which the user is prompted to enter an integer, and then a float, each of which uses a square function to determine the square. Using function templates based on argument types, C generates separate functions to properly manage each type of call. All definitions of function templates begin with a keyword template, followed by arguments enclosed in angle brackets <and>. For the type of data to be tested, one formal parameter T is used.
Consider the following program, in which the user is prompted to enter an integer, and then a float, each of which uses a square function to determine the square.
#include <iostream> using namespace std; template <class T> // function template T square(T); /* returns a value of type T and accepts type T (int or float or whatever) */ void main() { int x, y; float w, z; cout << "Enter a integer: "; cin >> x; y = square(x); cout << "The square of that number is: " << y << endl; cout << "Enter a float: "; cin >> w; z = square(w); cout << "The square of that number is: " << z << endl; } template <class T> // function template T square(T u) //accepts a parameter u of type T (int or float) { return u * u; } Here is the output: Enter a integer: 5 The square of that number is: 25 Enter a float: 5.3 The square of that number is: 28.09
source share