How to create a generic method in C++

1 Answer

0 votes
#include <iostream>

// Generic method (function template)
template <typename T>
void swapValues(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    // Swap integers
    int x = 10, y = 20;
    std::cout << "Before swap (int): x = " << x << ", y = " << y << "\n";
    swapValues(x, y);
    std::cout << "After swap  (int): x = " << x << ", y = " << y << "\n" << "\n";

    // Swap doubles
    double d1 = 3.14, d2 = 6.28;
    std::cout << "Before swap (double): d1 = " << d1 << ", d2 = " << d2 << "\n";
    swapValues(d1, d2);
    std::cout << "After swap  (double): d1 = " << d1 << ", d2 = " << d2 << "\n" << "\n";

    // Swap strings
    std::string s1 = "Hello", s2 = "World";
    std::cout << "Before swap (string): s1 = " << s1 << ", s2 = " << s2 << "\n";
    swapValues(s1, s2);
    std::cout << "After swap  (string): s1 = " << s1 << ", s2 = " << s2 << "\n";
}


/*
run:

Before swap (int): x = 10, y = 20
After swap  (int): x = 20, y = 10

Before swap (double): d1 = 3.14, d2 = 6.28
After swap  (double): d1 = 6.28, d2 = 3.14

Before swap (string): s1 = Hello, s2 = World
After swap  (string): s1 = World, s2 = Hello

*/

 



answered 4 hours ago by avibootz
...