Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,705 questions

55,464 answers

573 users

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 Apr 22 by avibootz
...