1. Goals
Write a function or class pattern that works with several types.
Distinguish type deduction from an explicit type argument.
Read an error caused by a type missing an operation used in a template.
2. Prerequisites
You know functions, overloads, classes, constructors, references, value
copying, std::string, and std::vector. You do not need metaprogramming
to write the small templates in this lesson.
3. Explanation
When two functions differ only in using int or double, copying their
bodies makes you maintain the same algorithm twice. A template is a
pattern describing a family of functions or classes. The declaration
template <typename T> names a type parameter T; class T also works
in this type parameter declaration.
larger accepts two values of type T, compares them, and returns a value
of that type. In larger(4, 7), the compiler deduces T as int from
both arguments. Producing the required version from the pattern is called
template instantiation. This happens during compilation; the program
does not change its types at runtime.
larger(4, 6.5); cannot deduce a consistent T: the first argument
suggests int and the second suggests double. Unlike calling a function
whose parameter type is already double, deduction here does not search
for a common numeric type. larger<double>(4, 6.5) explicitly selects
double, and the argument 4 is then converted to double. Choose the
type carefully: larger<int>(4, 6.5) loses the fractional part.
A template does not promise to support every type. larger needs to copy
its arguments and returned value; left < right must be valid and usable
as a condition. std::string supports these operations: the example
compares ASCII names lexicographically, not by their length. Do not pass
the literals "Lan" and "Minh" directly and assume content comparison;
they can be deduced as pointers. Construct std::string values as shown.
Trying these two lines separately inside main fails because NoOrder
does not define <. This type-dependent error is detected when the
function version is instantiated, even though the template itself was
syntactically valid:
struct NoOrder {};
(void)larger(NoOrder{}, NoOrder{});Box<int> and Box<std::string> are distinct class types. Box<T> owns
a T member by value; its constructor copies the argument and set
assigns to the member. These operations require the corresponding copy
operations from T. This lesson always spells out the class's type
argument, without introducing C++17 class template argument deduction.
get() returns const T& for reading the member owned by the box. That
reference must not outlive the box and is not an independent snapshot.
Copying a Box<std::string>, however, copies its string; changing the
original box does not change the copy. Templates still need clear
ownership rules, just like the classes from stage 3.
The example defines each template before using it. When splitting code
into files, the usual approach is to put template definitions in a header
included wherever instantiation is needed. A declaration in a header
with all definitions hidden in a separate .cpp file is usually
insufficient. Explicit instantiation is a later topic; the next lesson
focuses on separating ordinary functions.
4. Runnable example
Compile as C++17. The program does not read keyboard input.
#include <iostream>
#include <string>
template <typename T>
T larger(T left, T right) {
return left < right ? right : left;
}
template <typename T>
class Box {
T value_;
public:
explicit Box(const T& value) : value_(value) {}
const T& get() const { return value_; }
void set(const T& value) { value_ = value; }
};
int main() {
std::cout << "Larger integer: " << larger(4, 7) << '\n';
std::cout << "Explicit double: " << larger<double>(4, 6.5) << '\n';
std::cout << "Later name: "
<< larger(std::string("Lan"), std::string("Minh")) << '\n';
Box<int> count(5);
count.set(8);
std::cout << "Count: " << count.get() << '\n';
Box<std::string> topic("Classes");
Box<std::string> snapshot = topic;
topic.set("Templates");
std::cout << "Current topic: " << topic.get() << '\n';
std::cout << "Copied topic: " << snapshot.get() << '\n';
return 0;
}Output:
Larger integer: 7
Explicit double: 6.5
Later name: Minh
Count: 8
Current topic: Templates
Copied topic: Classes5. Common mistakes
Treating
Tas a value variable you can assign at runtime.Passing two different types and expecting deduction to choose a common one.
Reading library errors while overlooking the call site and argument type.
Assuming every copyable class also has
<.Returning a reference to a local parameter of
largerto avoid copying.Keeping a reference from
get()after its box has been destroyed.Creating complicated templates merely to avoid a few clear lines of code.
6. Practice
Call
larger(-3, -8)andlarger(5, 5): expect-3and5. Withstd::stringvalues"Z"and"Apple", expect"Z"even though it is the shorter string.Try
larger(4, 6.5);and theNoOrderexample separately: both must fail compilation. Explain why the first is a deduction error and the second concerns an operation on the type. Fix the first withlarger<double>.Create a
Box<std::string>namedoriginaland copy it tocopy. Aftercopy.set("New"),originalmust retain its old value. Try aconst Box<int>: you may callgetbut cannot callset.Write
smaller(T left, T right)returning the smaller value, then test integers, floating-point numbers, andstd::string. State its copying and comparison requirements; specialization, SFINAE, and concepts are unnecessary here.
7. Self-check
How do
larger(4, 6.5)andlarger<double>(4, 6.5)differ? Answer: the first deduces conflicting types for the sameT. The second selectsdoublefirst and converts4to that type.Why can
Box<NoOrder>work whilelargerwithNoOrderfails? Answer: the simple copy operations ofNoOrderwork for the box.largeradditionally needs<, which this type does not provide.Does
const std::string& view = topic.get();make a copy? Answer: no.viewborrows the member insidetopicand needs that box to remain alive. Copying the wholeBox<std::string>creates a string owned by an independent box.
Sample code
Source file
cpp98_foundation/23_templates/main.cpp
#include <iostream>
#include <string>
template <typename T>
T larger(T left, T right) {
return left < right ? right : left;
}
template <typename T>
class Box {
T value_;
public:
explicit Box(const T& value) : value_(value) {}
const T& get() const { return value_; }
void set(const T& value) { value_ = value; }
};
int main() {
std::cout << "Larger integer: " << larger(4, 7) << '\n';
std::cout << "Explicit double: " << larger<double>(4, 6.5) << '\n';
std::cout << "Later name: "
<< larger(std::string("Lan"), std::string("Minh")) << '\n';
Box<int> count(5);
count.set(8);
std::cout << "Count: " << count.get() << '\n';
Box<std::string> topic("Classes");
Box<std::string> snapshot = topic;
topic.set("Templates");
std::cout << "Current topic: " << topic.get() << '\n';
std::cout << "Copied topic: " << snapshot.get() << '\n';
return 0;
}