Write a class that works for any type.
What to build
A class template with a few methods.
Requirements
- Write
Duo<T>with a constructor taking two values. first()andsecond()return the values, and areconst.swap_values()exchanges them.- Do not change
main.
Input
One line with two whole numbers and two words.
Output
Two lines, printed by main.
Constraints
Each word has at most 20 letters.
Example
Input:
1 2 a b
Output:
2 1
b a
Why it works
Writing Duo<int> and Duo<string> makes the compiler produce a separate class for each, from one definition.
Examples
Example 1 · Input
1 2 a b
Expected output
2 1 b a
Example 2 · Input
5 5 x x
Expected output
5 5 x x
Hints
Hint 1
Write template <typename T> above the class.
Hint 2
Store two private values of type T.
Hint 3
swap_values can use a temporary variable of type T.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Duo {
T a_;
T b_;
public:
Duo(T a, T b) : a_(a), b_(b) {}
T first() const { return a_; }
T second() const { return b_; }
void swap_values() {
T temp = a_;
a_ = b_;
b_ = temp;
}
};
int main() {
int a, b;
string c, d;
cin >> a >> b >> c >> d;
Duo<int> x(a, b);
Duo<string> y(c, d);
x.swap_values();
y.swap_values();
cout << x.first() << " " << x.second() << endl;
cout << y.first() << " " << y.second() << endl;
return 0;
}