How to swap two variables using class template in C++

1 Answer

0 votes
#include <iostream>

template<class T>
class Example {
public:
    T a, b;
    Example(T x, T y) : a(x), b(y) {}   // constructor
    
    void swap();
};

template<class T>
void Example<T>::swap() {
    T tmp = a;
    a = b;
    b = tmp;
}


int main() {
    int x = 10;
    int y = 25;
    
    Example<int> obj(x, y);
    
    std::cout << obj.a << " " << obj.b << "\n";
    
    obj.swap(); 

    std::cout << obj.a << " " << obj.b;
}




/*
run:

10 25
25 10

*/

 



answered Dec 5, 2022 by avibootz

Related questions

1 answer 136 views
2 answers 182 views
1 answer 243 views
1 answer 242 views
1 answer 153 views
1 answer 144 views
1 answer 143 views
...