Templated mySwap( ) Function

Learn to create a templated function that works on four different data types.

Problem

Write a template function, myswap( ), that interchanges the contents of two variables. Use it to swap integers, floats, long integers, and strings. Can this function be given a name swap( ) instead of myswap( )?

Sample run

Suppose x and y are int variables, i and j are float variables, u and v are double variables, and str1 and str2 are string variables with initial values. If we display their values in that order, before and after calling swap() on each pair of values, we should get an output similar to the following:

Before swapping:
x = 10  y = 20
i = 1.5 j = 2.5
u = 10.23       v = 20.45
str1 = Mumbai   str2 = Nagpur
After swapping:
x = 20  y = 10
i = 2.5 j = 1.5
u = 20.45       v = 10.23
str1 = Nagpur   str2 = Mumbai

Coding exercise

Your job is to define a templated mySwap( ) function in the code given below.

Get hands-on with 1200+ tech skills courses.