[Solved] I do not understand the template? can you help me? [closed]


The really smart answer is:

#include <algorithm>

As in:

#include <iostream>
#include <algorithm>

main() {
    int x = 1, y = 2;
    std::swap <int> (x, y);
    std::cout << "Expecting 2: " << x << std::endl;
    std::cout << "Expecting 1: " << y << std::endl;
}

Because swap is already included in <algorithm>!

The best C++ way is to use what’s already in the library. Knowing what’s there will help you write clean, minimal, and robust code.

If you have to roll your own, then just copy the code from cplusplus and change it up a bit, here I changed c to t and slid the &s over:

#include <iostream>

template <class T>
void swap (T &a, T &b) {
    T t(a);
    a = b;
    b = t;
}

main() {
    int x = 1, y = 2;
    swap <int> (x, y);
    std::cout << "Expecting 2: " << x << std::endl;
    std::cout << "Expecting 1: " << y << std::endl;
}

4

solved I do not understand the template? can you help me? [closed]