Templates: run-time versus compile-time polymorphism
What you will learn on this page
Section titled “What you will learn on this page”- How to write a function template and a class template.
- How a C++20 concept states what a template needs from its types.
- The difference between run-time polymorphism (virtual functions) and compile-time polymorphism (templates).
- How to choose between them, by flexibility, speed, code size, error messages, and how code is shipped.
One job, two kinds of polymorphism
Section titled “One job, two kinds of polymorphism”Polymorphism means one piece of code working with several types. The inheritance lesson showed one way: code calls a virtual function through an interface, and the object’s real type decides, at run time, which implementation runs. Templates are the other way: code is written once with a placeholder type, and the compiler produces a version for each type it is used with, at compile time.
This lesson writes one job both ways. A checkout adds up item prices (in whole cents), adjusting each price by a pricing rule: no discount, a percentage off, half price.
The run-time form: an interface
Section titled “The run-time form: an interface”This is the shape from the inheritance lesson:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Interface: how one item's price is adjusted. It has no data and no code of// its own; each derived class (PercentOff, NoDiscount, ...) supplies price().// Code that holds a PricingRule* or PricingRule& calls price() without// knowing which class it really has: the object decides, at run time.class PricingRule {public: // Virtual destructor: deleting a derived rule through a PricingRule // pointer (which unique_ptr<const PricingRule> does) runs the derived // class's destructor too. virtual ~PricingRule() = default; // Takes the item's normal price in cents and returns the price to // charge. `virtual ... = 0` makes it "pure": PricingRule has no version, // every concrete rule must override it, and no plain PricingRule object // can be created. [[nodiscard]] virtual int price(int base_cents) const = 0;
protected: // Construction, copy, and move are protected: only derived classes can // use them. A derived rule can still be copied as itself, but outside // code cannot assign one rule to another through two PricingRule // references, which would copy only the base part (slicing). PricingRule() = default; PricingRule(const PricingRule&) = default; PricingRule& operator=(const PricingRule&) = default; PricingRule(PricingRule&&) = default; PricingRule& operator=(PricingRule&&) = default;};
// Takes `percent` per cent off every price. `final` means no class can// derive from PercentOff; `public PricingRule` makes it usable wherever a// PricingRule is expected.class PercentOff final : public PricingRule {public: // Throws std::invalid_argument unless 0 <= percent <= 100, so a // PercentOff that exists always holds a sensible percentage. explicit PercentOff(int percent); // `override` asks the compiler to check that this really replaces the // base class's virtual price(); a typo in the signature becomes an error. int price(int base_cents) const override; // rounds down
private: int percent_;};
// The rule that changes nothing: every item costs its base price.class NoDiscount final : public PricingRule {public: int price(int base_cents) const override { return base_cents; }};
// Chooses a rule from configuration text such as "none" or "percent-off:10".// Throws std::invalid_argument for anything else, including a percentage// outside 0..100. Returns a new rule that the caller owns: the return type// std::unique_ptr<PricingRule> is the single owner of the object and deletes// it when it goes away. The caller only sees "some PricingRule"; which class// it is was decided by the text, while the program runs.[[nodiscard]] std::unique_ptr<PricingRule> rule_from_config(std::string_view text);
// A checkout that adds up scanned prices using a rule chosen at run time.// Invariant: rule_ is not null (except after being moved from).class RuntimeCheckout {public: // Both take a unique_ptr by value: the caller hands the rule over (with // std::move, or straight from rule_from_config), and the checkout owns it // from then on. `const PricingRule` means the checkout only ever calls // const functions such as price() on it. A unique_ptr<PricingRule> // converts to unique_ptr<const PricingRule> automatically. // Both throw std::invalid_argument if given a null pointer. explicit RuntimeCheckout(std::unique_ptr<const PricingRule> rule); void set_rule(std::unique_ptr<const PricingRule> rule); // Remembers one item's base price; the rule is applied later, by total(). void scan(int base_cents) { items_.push_back(base_cents); } // Sum of rule_->price(item) over every scanned item, using the rule // held now: after set_rule, the same items are priced the new way. [[nodiscard]] int total() const;
private: std::unique_ptr<const PricingRule> rule_; // owned; the object is a derived rule std::vector<int> items_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stores the percentage, then refuses a bad one. Throwing from a constructor// means the object never comes into existence, so no PercentOff can hold// 150 or -5.PercentOff::PercentOff(int percent) : percent_(percent) { if (percent < 0 || percent > 100) throw std::invalid_argument("percent must be 0 to 100");}
// Multiply first, then divide, all in whole numbers: 10% off 850 is// 850 * 90 / 100 = 76500 / 100 = 765. Dividing last keeps the result exact// until the final step, which drops any fraction of a cent (rounds down).int PercentOff::price(int base_cents) const { return base_cents * (100 - percent_) / 100; }
// Turns configuration text into a rule object. See the walkthrough below.std::unique_ptr<PricingRule> rule_from_config(std::string_view text) { // std::make_unique<NoDiscount>() creates a NoDiscount on the heap and // returns its owner; it converts to the unique_ptr<PricingRule> returned. if (text == "none") return std::make_unique<NoDiscount>(); constexpr std::string_view prefix = "percent-off:"; // Does the text start with the prefix? substr(0, n) is the first n // characters (or fewer, if the text is shorter, which then cannot match). if (text.substr(0, prefix.size()) == prefix) { // Everything after the prefix: "10" for "percent-off:10". A // string_view is a window onto the same characters; nothing is copied. const std::string_view number = text.substr(prefix.size()); int percent = 0; // std::from_chars reads an int from the characters between the two // pointers (start, one past the end). It returns two things, unpacked // here by a structured binding: `end`, where it stopped reading, and // `error`, a std::errc that is std::errc{} (no error) on success. It // never throws. const auto [end, error] = std::from_chars(number.data(), number.data() + number.size(), percent); // Accept only if a number was read AND it used every character: // "20x" reads 20 but stops before the "x", so `end` is not the end. if (error == std::errc{} && end == number.data() + number.size()) { // PercentOff's constructor still checks the range: "percent-off:120" // gets this far and then throws std::invalid_argument there. return std::make_unique<PercentOff>(percent); } } // Every text that did not return above ends here. throw std::invalid_argument("unknown pricing rule");}
// The constructor reuses set_rule, so the null check is written once.// std::move hands the pointer on: a unique_ptr cannot be copied.RuntimeCheckout::RuntimeCheckout(std::unique_ptr<const PricingRule> rule) { set_rule(std::move(rule));}
// Check first, then change: a null rule throws before rule_ is touched, so// the checkout keeps its old rule. Assigning a new owner to rule_ deletes the// rule it held before.void RuntimeCheckout::set_rule(std::unique_ptr<const PricingRule> rule) { if (rule == nullptr) throw std::invalid_argument("a checkout needs a pricing rule"); rule_ = std::move(rule);}
// `rule_->price(base)` is a virtual call: the program looks up, while it// runs, which class rule_ really points at, and calls that class's price.int RuntimeCheckout::total() const { int sum = 0; for (const int base : items_) sum += rule_->price(base); // virtual call return sum;}How this code works: rule_from_config
rule_from_config turns a line of configuration text into a rule object, or
refuses it. It has three ways out: two returns for the texts it understands,
and one throw at the bottom that every other text falls through to.
"none"returns a newNoDiscountat once.- The prefix test.
text.substr(0, prefix.size())is the first 12 characters of the text ("percent-off:"is 12 long). If they are not the prefix, the wholeifis skipped and the function throws. - The number.
numberis everything after the prefix.std::from_charstries to read anintfrom the start of it, writes the value intopercentif it succeeds, and reports where it stopped (end) and whether it failed (error). It never throws; failure is reported inerror. - Two conditions, both needed.
error == std::errc{}means a number was read.end == number.data() + number.size()means reading stopped at the very end, so there was nothing after the digits. - The range. The parser does not check 0 to 100 itself. It passes
percenttoPercentOff’s constructor, which throwsstd::invalid_argumentfor a bad value. The rule’s own constructor guards its own data, wherever the value came from.
Each case in the tests, traced:
| Text | What happens | Result |
|---|---|---|
"none" |
first if matches |
a NoDiscount |
"percent-off:20" |
prefix matches, reads 20, end is the end |
a PercentOff(20) |
"percent-off:" |
prefix matches, number is empty, nothing can be read |
throws (bottom line) |
"percent-off:20x" |
reads 20 but stops before x, so end is not the end |
throws (bottom line) |
"percent-off:120" |
reads 120 cleanly, then PercentOff(120) refuses it |
throws (from PercentOff) |
"half" |
neither "none" nor the prefix |
throws (bottom line) |
In RuntimeCheckout, the constructor calls set_rule, so the “not null”
check lives in one place. set_rule checks before it changes rule_, so
a refused nullptr leaves the old rule in place, which is what the test
runtime_rule_can_be_replaced checks.
RuntimeCheckout holds “some pricing rule” through
std::unique_ptr<const PricingRule>, and total calls price virtually. The
rule is an ordinary run-time value: rule_from_config builds one from text, and
set_rule can replace it at any moment. One compiled RuntimeCheckout works
with every rule, including rule classes written years later in another library.
The compile-time form: templates
Section titled “The compile-time form: templates”A function template
Section titled “A function template”A function template is a function with a type parameter:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds up the prices in base_cents after applying `rule` to each one.// `template <PricingRuleLike Rule>` makes Rule a type parameter that must// satisfy the concept. The compiler works out Rule from the second argument// (total_price(prices, PercentOff(10)) gives Rule = PercentOff) and writes a// separate copy of this function for each Rule type it is called with.// Both arguments are const references: read, never copied or changed.template <PricingRuleLike Rule>[[nodiscard]] int total_price(const std::vector<int>& base_cents, const Rule& rule) { int sum = 0; // An ordinary, non-virtual call: in total_price<HalfPrice>, this is // exactly HalfPrice::price, so the compiler can inline it. for (const int base : base_cents) sum += rule.price(base); return sum;}template <PricingRuleLike Rule> introduces a type parameter named Rule (the
PricingRuleLike part is explained below; plain template <typename Rule> would
also work). When code calls total_price(prices, PercentOff(10)), the compiler
deduces Rule = PercentOff from the argument and instantiates the
template: it generates a real function, total_price<PercentOff>, with Rule
replaced by PercentOff. Calling it with a HalfPrice generates a second, separate
function.
Inside each generated function, rule.price(base) is a plain call to a known
function, so the compiler can inline it. No base class, no virtual call, no
pointer.
Because the compiler needs the template’s body to generate each version, a
template is normally defined in the header, not in a .cpp file. (The exception
is a template that is explicitly instantiated in a .cpp file for a fixed list
of types; other types then cannot be used with it.)
A class template
Section titled “A class template”A class template is a class with a type parameter:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A rule type with no base class and no virtual functions. It satisfies// PricingRuleLike only because it has the right price() function.// Integer division drops the fraction: 425 / 2 is 212, not 212.5.struct HalfPrice { [[nodiscard]] int price(int base_cents) const { return base_cents / 2; }};
// A checkout whose rule type is part of its own type: Checkout<HalfPrice>// is a class the compiler generates from this template with Rule replaced// by HalfPrice. Different Rule types give different, unrelated classes.template <PricingRuleLike Rule>class Checkout {public: // Takes the rule by value and moves it into the member: the checkout // keeps its own copy, and std::move avoids copying it a second time. explicit Checkout(Rule rule) : rule_(std::move(rule)) {} void scan(int base_cents) { items_.push_back(base_cents); } // Reuses the function template above; Rule is deduced from rule_. [[nodiscard]] int total() const { return total_price(items_, rule_); }
private: Rule rule_; // held by value: the type is known, so no pointer is needed std::vector<int> items_;};Checkout<HalfPrice> is a class generated from the template, with a HalfPrice
member. The rule is held by value: its exact type is known, so no pointer and
no allocation are needed. HalfPrice has no base class and no virtual functions;
it only has to have the right price function.
But Checkout<HalfPrice> and Checkout<NoDiscount> are different, unrelated
types. They cannot be stored in the same std::vector, passed to the same
non-template function, or swapped for each other at run time. The class of a
Checkout<Rule>’s rule is fixed by its type; the rule’s settings, such as the
percentage in a Checkout<PercentOff>, can still come from configuration.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Runtime: the rule comes from configuration and can change later.// rule_from_config returns a new unique_ptr, handed straight to the// checkout, which owns the rule from then on.RuntimeCheckout till(rule_from_config("percent-off:10"));till.scan(1200);till.scan(850);// 1200 * 90 / 100 = 1080 and 850 * 90 / 100 = 765, so this prints 1845.std::cout << "runtime, 10% off: " << till.total() << '\n';// Same checkout, same items, new rule: the old PercentOff is deleted// when set_rule replaces it, and the total becomes 1200 + 850 = 2050.till.set_rule(rule_from_config("none"));std::cout << "runtime, no discount: " << till.total() << '\n';
// Compile time: the rule's type is part of the checkout's type.// HalfPrice{} makes a HalfPrice object (it has no data to set).// 1200 / 2 + 850 / 2 = 600 + 425 = 1025.Checkout<HalfPrice> sale(HalfPrice{});sale.scan(1200);sale.scan(850);std::cout << "template, half price: " << sale.total() << '\n';
// The function template accepts any type that satisfies the concept,// including the runtime form's classes.// Below, PercentOff(10) is a temporary object that lives until the end of// that statement, long enough for total_price to use it. No pointer needed.const std::vector<int> prices{1200, 850};std::cout << "template, 10% off: " << total_price(prices, PercentOff(10)) << '\n';runtime, 10% off: 1845runtime, no discount: 2050template, half price: 1025template, 10% off: 1845The last line passes a PercentOff, one of the run-time form’s classes, to the
function template. It works because PercentOff has the price function the
template needs; the template does not care about its base class.
Concepts: saying what a template needs
Section titled “Concepts: saying what a template needs”A template places requirements on its types: total_price calls
rule.price(base) and adds the result to an int. Before C++20, those
requirements existed only in the body. C++20 lets you name them as a concept:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Any type with a const price(int) that returns int is a pricing rule.// No base class is needed.// Read it as: "a type Rule is PricingRuleLike if, given a const Rule called// rule and an int called base_cents, this expression compiles and its type// is exactly int". Nothing here runs; the compiler only checks it.template <typename Rule>concept PricingRuleLike = requires(const Rule& rule, int base_cents) { // { expression } -> constraint: the expression must be valid, and its // result type must satisfy std::same_as<int> (be int, not double or long). { rule.price(base_cents) } -> std::same_as<int>;};The requires expression lists what must compile for a type to qualify: given a
const Rule& rule and an int, rule.price(base_cents) must be valid, and its
result type must be exactly int (std::same_as<int>). Writing
template <PricingRuleLike Rule> instead of template <typename Rule> makes the
template accept only such types.
That has two effects, both observed with GCC 11.4 and Clang 14 on this site’s build machine:
- Errors point at the call. Passing a rule type whose
pricereturnsdoublegives an error at the call site saying that the type does not satisfyPricingRuleLike, and naming the requirement that failed (the return type). Without the concept, an error, when there is one, is reported inside the template’s body, with the call site as a note (“in instantiation of…”). For a small template like this one that is still readable; for templates that call other templates, the messages become long. - Mistakes that compile without it are rejected. Without the concept, a rule
whose
pricereturnsdoubleis accepted: thedoubleis silently converted tointwhen added tosum, dropping any fraction of a cent. Both compilers accept that unconstrained version even with this site’s-Wall -Wextra -Wpedantic -Werror. The concept turns it into an error.
A concept is also documentation: PricingRuleLike says in one line what a rule
must provide, which is the same job an interface does for the run-time form.
Testing both forms
Section titled “Testing both forms”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records a// failure, printing both values, unless they are equal, and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws that// type of exception. They come from the site's small test header,// lld_test.hpp.
// A rule type written only for the tests: neither form needs changing.// Every item costs `cents`, whatever its base price; the unnamed int// parameter says "this argument is deliberately not used".struct FixedPrice { int cents; [[nodiscard]] int price(int) const { return cents; }};
// static_assert(condition) is checked by the compiler: if the condition is// false, the file does not compile. So these lines test the concept before// any test runs. PricingRuleLike<X> is true or false for each type X.static_assert(PricingRuleLike<HalfPrice>);static_assert(PricingRuleLike<PercentOff>); // the runtime classes qualify toostatic_assert(PricingRuleLike<FixedPrice>);static_assert(!PricingRuleLike<int>); // an int has no price() at allstatic_assert(!PricingRuleLike<std::string>); // nor does a string
// The same prices through the virtual form and the template form must give// the same total. 25% off: 999 * 75 / 100 = 749, 1 * 75 / 100 = 0 (the// fraction is dropped), 250 * 75 / 100 = 187.LLD_TEST(both_forms_agree) { const std::vector<int> prices{999, 1, 250}; RuntimeCheckout till(std::make_unique<PercentOff>(25)); for (const int price : prices) till.scan(price); LLD_CHECK_EQ(till.total(), total_price(prices, PercentOff(25))); LLD_CHECK_EQ(till.total(), 749 + 0 + 187); // each item rounds down}
// Checkout<FixedPrice> charges 100 for each item, so two items cost 200// whatever was scanned. A checkout with no items totals 0.LLD_TEST(class_template_uses_its_rule) { Checkout<FixedPrice> checkout(FixedPrice{100}); checkout.scan(5); checkout.scan(5000); LLD_CHECK_EQ(checkout.total(), 200); LLD_CHECK_EQ(Checkout<HalfPrice>(HalfPrice{}).total(), 0);}
// set_rule swaps the rule while the program runs; the items stay. A null// rule is refused with an exception and leaves the old rule in place.LLD_TEST(runtime_rule_can_be_replaced) { RuntimeCheckout till(std::make_unique<NoDiscount>()); till.scan(1000); LLD_CHECK_EQ(till.total(), 1000); till.set_rule(std::make_unique<PercentOff>(50)); LLD_CHECK_EQ(till.total(), 500); LLD_CHECK_THROWS(till.set_rule(nullptr), std::invalid_argument); LLD_CHECK_EQ(till.total(), 500); // a rejected rule changes nothing}
// Good texts give the right rule (20% off 1000 is 800). Each bad text throws:// no number after the colon, a number followed by junk, a number outside// 0..100 (refused by PercentOff's constructor), and an unknown rule name.// rule_from_config(...)->price(1000) calls price on the returned rule; the// temporary unique_ptr deletes it at the end of the statement.LLD_TEST(configuration_is_parsed_strictly) { LLD_CHECK_EQ(rule_from_config("percent-off:20")->price(1000), 800); LLD_CHECK_EQ(rule_from_config("none")->price(1000), 1000); LLD_CHECK_THROWS(rule_from_config("percent-off:"), std::invalid_argument); LLD_CHECK_THROWS(rule_from_config("percent-off:20x"), std::invalid_argument); LLD_CHECK_THROWS(rule_from_config("percent-off:120"), std::invalid_argument); LLD_CHECK_THROWS(rule_from_config("half"), std::invalid_argument);}The static_assert lines test the concept itself at compile time: the right
types qualify, and int and std::string do not. FixedPrice, written only for
the tests, works with the templates without inheriting from anything, which is
the compile-time form’s version of a test double. The first test checks that both
forms give the same totals for the same prices.
Comparing the two forms
Section titled “Comparing the two forms”| Question | Virtual functions (run time) | Templates (compile time) |
|---|---|---|
| When is the implementation chosen? | While the program runs, for example from configuration | When the code is compiled |
| Mixing types in one collection | Yes: std::vector<std::unique_ptr<PricingRule>> |
No: Checkout<A> and Checkout<B> are unrelated types |
| Replacing the implementation later | Yes, set_rule |
Only by creating a different object of a different type |
| What a type must do | Inherit from the interface | Have the required operations (stated by a concept) |
| Call cost | An indirect call, not inlined unless the compiler can see the exact type | A direct call, which can be inlined |
| Code size | One copy of the calling code | One copy per type used; more types, more code |
| Where the code lives | Implementations can be in .cpp files, compiled once |
Definitions must be in headers; every user recompiles them |
| Changing the implementation | The library can change without recompiling users, if the interface stays the same | Users recompile; the template is part of their code |
| Errors | At the call, or in the implementing class | At the call with a concept; otherwise inside the template |
The last two rows matter most for libraries. A virtual interface can be the boundary between separately compiled parts of a system, even between a program and a plug-in, as long as both sides agree on the interface’s binary layout (its ABI). A template defined in a header cannot be that kind of boundary for its own code: it is compiled into each user’s program, so changing it means recompiling the users.
The call-cost row is real but usually small. It matters for an operation called
millions of times in a loop, such as a comparison inside a sort, and rarely for
an operation like price next to everything else a checkout does. Measure before
choosing a template for speed alone.
When to use which
Section titled “When to use which”Use virtual functions when:
- the implementation is chosen or changed at run time (configuration, user choice, plug-ins);
- different implementations must sit together in one collection;
- the code must be a stable, separately compiled boundary, such as a library interface.
Use templates when:
- the type is known when compiling, and every use names it (as with
std::vector<int>or a comparison passed tostd::sort); - the operation is small and called very often, so inlining matters;
- the types involved should not have to inherit from anything, such as built-in types, standard types, or lambdas.
When neither fits well, there are two middle grounds: a std::variant of a fixed
set of rule types with std::visit (a closed set, chosen at run time, held by
value), and std::function (any callable, chosen at run time). Later lessons
compare them.
Common mistakes
Section titled “Common mistakes”- Making everything a template “for performance”. It costs compile time, header size, and readability, and the run-time choice disappears. Start with the simpler form for the job.
- Putting a template’s definition in a
.cppfile. Other files cannot instantiate it, and linking fails with “undefined reference” (unless the.cppfile explicitly instantiates every type that is used). - Unconstrained templates with surprising requirements. Name the requirements with a concept, so mistakes are caught at the call and do not compile silently.
- Expecting
Checkout<A>andCheckout<B>to be interchangeable. They are different types. If they must be, you need run-time polymorphism. - A virtual interface for a choice that is always fixed when compiling, in a hot loop. It works, but costs an indirect call for flexibility nobody uses.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Shops choose their pricing rule in a configuration file, and can change it without restarting the till.”
The run-time form already does this: rule_from_config turns text into a rule,
and set_rule replaces it. The compile-time form can read a percentage from configuration, but it cannot
switch from PercentOff to HalfPrice, because the rule’s class is part of the
checkout’s type. If the template had been the only form, there would be two
options. One is to introduce the interface. The other is to give the template a
rule type that holds a std::function<int(int)> chosen at run time, which is
run-time polymorphism again under another name.
The reverse requirement, “price a million basket items per second in a batch job, always with the same rule”, is where the template’s direct, inlinable call can help. Even then, measure first.
Exercise: Run time or compile time?
For each scenario, choose virtual functions or templates (or something else), and give the deciding reason.
- A payment service supports card, bank transfer, and gift card. Which one is used is chosen per payment, by the customer.
- A small numeric library offers
Vector3<T>forfloatanddouble, used in physics code that runs millions of times per frame. - A desktop application loads export formats from plug-ins written by other companies, shipped as separate shared libraries.
- A function sorts members by a comparison that the caller passes in, usually a lambda.
Show the explained answer
- Virtual functions (a
PaymentMethodinterface). The choice is made at run time, per payment, and different payment objects may need to be handled by the same code. Astd::variantof the three methods is also reasonable if the set is fixed and small. - Templates. The element type is known when compiling, every use names it
(
Vector3<float>), the operations are tiny and very frequent, andfloatanddoublecannot inherit from anything. - Virtual functions. The plug-ins are compiled separately by others, so the boundary must be a stable, separately compiled interface. A template cannot cross it. Even a virtual interface is fragile between code built by different compilers or compiler versions; plug-in systems that must be fully robust often use a plain C interface at the boundary.
- A template taking the comparison as a type parameter, as
std::sortdoes. Each lambda has its own type, the comparison is called many times inside the sort, and inlining it is a real benefit. If the comparison had to be stored and chosen at run time,std::functionwould fit instead.
Summary
Section titled “Summary”- A function or class template is written once with type parameters; the compiler generates a separate version for each type it is used with.
- Run-time polymorphism (virtual functions) chooses the implementation while the program runs; compile-time polymorphism (templates) chooses it when compiling.
- A concept names a template’s requirements, so mistakes are reported at the call and do not compile silently.
- Choose virtual functions for run-time choice, mixed collections, and stable library boundaries; choose templates for types known when compiling, very frequent small operations, and types that cannot inherit.