4 Examples
4 Examples
#include <iostream>
#include <string>
#include <vector>
int main(){
bool t = true;
bool f = false;
std::cout << "(t, f): (" << t << ", " << f << ") "<< std::endl;
xchg(t, f);
std::cout << "(t, f): (" << t << ", " << f << ") "<< std::endl;
std::cout << "(int2011, int2014): (" << int2011 << ", " << int2014 << ") "<< std::endl;
std::string first{"first"};
std::string second{"second"};
std::cout << "(first, second): (" << first << ", " << second << ") "<< std::endl;
xchg(first, second);
std::cout << "(first, second): (" << first << ", " << second << ") "<< std::endl;
Explanation #
In the example above, we’ve declared two function templates: xchg and
nTimes in lines 8 and 15. xchg swaps the values passed as arguments. The
only non-type, we use is N in the function templates nTimes . nTimes returns
the N times of the number passed n . We have initialized multiple instances to
check for functions in lines 31 and 32, lines 39 and 40, and lines 46 and 47.
int main(){
int intA = 5;
int intB = 10;
int intC = 20;
std::cout << "Before: " << intA << ", " << intB << std::endl;
xchg(intA, intB); // 1
std::cout << "After: " << intA << ", " << intB << std::endl;
std::cout << "Before: " << doubleA << ", " << doubleB << std::endl;
xchg(doubleA, doubleB); // 2
std::cout << "After: " << doubleA << ", " << doubleB << std::endl;
std::cout << "Before: " << intA << ", " << intB << ", " << intC << std::endl;
xchg(intA, intB, intC); // 3
std::cout << "After: " << intA << ", " << intB << ", " << intC << std::endl;