Write one function or class that works for any type; the compiler makes a version per type used.
C++ · beginner · 7 min · 14 steps · free
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T biggest(T a, T b) {
return a > b ? a : b;
}
template <typename T>
class Box {
T item;
public:
Box(T i) : item(i) {}
T get() const { return item; }
};
int main() {
int i = biggest(3, 9); // T is int
double d = biggest(2.5, 1.5); // T is double
Box<string> label("fragile"); // T is string
string text = label.get();
cout << i << " " << d << " " << text << endl;
return 0;
}a > b ? a : b.biggest<int>() has finished, so its variables are gone. The value it returned, 9, is stored in i.a > b ? a : b.biggest<double>() has finished, so its variables are gone. The value it returned, 2.5, is stored in d.Box() has finished, so its variables are gone. label is created on the stack with the value {item: "fragile"}.get(). It gets its own variables on the stack.get() has finished, so its variables are gone. The value it returned, "fragile", is stored in text.9 2.5 fragile.0.~Box() runs, because the object is going away.Answer: int. Deduced from the arguments.
Answer: A class template used with int. vector is a template.
← STL Algorithms and Lambdas · Exceptions: throw, try, catch →