Skip to content
LeetQuant
E12 Advanced C++

E12 · Advanced C++ · Lesson 1 of 5

Templates in Depth

How the compiler deduces template arguments, forwarding references and std::forward, variadic templates and fold expressions, SFINAE and why concepts replaced it, and CRTP for static polymorphism.

20 min

What you should be able to do after this lesson

The Modern C++ module used templates as a tool. Interviewers for low-latency roles go one level down: "what is T here?", "why does this overload not get picked?", "why did my wrapper copy instead of move?", "how would you avoid a virtual call?". This lesson gives you the rules behind those answers:

  1. The three template argument deduction cases, and the special rule that makes forwarding references work.
  2. Reference collapsing and what std::forward actually does.
  3. Variadic templates and the four forms of fold expression.
  4. SFINAE: how it works, and the concrete problems that made C++20 replace it with concepts.
  5. CRTP: compile-time polymorphism, and when it is worth the cost.

Every program here was compiled with Apple clang 17 using c++ -std=c++20 -O2 -Wall and the output shown is real.

Deduction: three cases

For template <class T> void f(P param) called as f(expr), the compiler matches the parameter type P against the type of expr. The answer depends on the shape of P:

ParameterWhat happens to the argument type
T (by value)references stripped, then top-level const/volatile stripped; arrays and functions decay to pointers
T& or const T&reference stripped, const kept as part of T; no decay
T&& (forwarding reference)lvalue of type A gives T = A&; rvalue gives T = A

A compiler will tell you what it deduced. Clang's __PRETTY_FUNCTION__ includes the template arguments:

#include <cstdio>

// Print the deduced T using the compiler's pretty function name (Clang's format).
template <class T> void by_value(T)  { std::puts(__PRETTY_FUNCTION__); }
template <class T> void by_ref(T&)   { std::puts(__PRETTY_FUNCTION__); }
template <class T> void by_fwd(T&&)  { std::puts(__PRETTY_FUNCTION__); }

int main() {
    const int ci = 7;
    const int& cr = ci;
    int arr[4] = {};

    by_value(ci);   // top-level const dropped
    by_value(cr);   // reference and const dropped
    by_value(arr);  // array decays to pointer
    by_ref(ci);     // const kept
    by_ref(arr);    // no decay
    by_fwd(ci);     // lvalue argument
    by_fwd(42);     // rvalue argument
}
void by_value(T) [T = int]
void by_value(T) [T = int]
void by_value(T) [T = int *]
void by_ref(T &) [T = const int]
void by_ref(T &) [T = int[4]]
void by_fwd(T &&) [T = const int &]
void by_fwd(T &&) [T = int]

The last two lines are the important ones. For an lvalue const int, T is deduced as const int&, so the parameter type T&& is const int& &&, which collapses to const int&. For the rvalue 42, T = int and the parameter is int&&. That asymmetry is the whole mechanism behind perfect forwarding.

Three more rules that cause interview bugs:

  • No conversions during deduction. With template <class T> T mx(T a, T b), the call mx(1, 2.0) fails: Clang says "deduced conflicting types for parameter 'T' ('int' vs. 'double')". Deduction looks for one T; it does not consider converting 1 to double.
  • Non-deduced contexts. A T that appears only inside typename Something<T>::type cannot be deduced. You can use this on purpose: template <class T> T mx2(T a, std::type_identity_t<T> b) deduces T from a only, so mx2(1.5, 2) compiles and converts 2 to double.
  • Braced lists. f({1, 2}) does not deduce T for a plain T parameter; auto x = {1, 2}; does deduce std::initializer_list<int>. This is the one place auto and template deduction differ.

Forwarding references and std::forward

T&& is a forwarding reference only when T is a template parameter deduced from that very argument (and auto&& likewise). std::vector<T>&& is an ordinary rvalue reference, and so is void push(T&& x) inside template <class T> class Queue, because T was fixed when the class was instantiated.

When deduction produces a reference to a reference, reference collapsing applies: if either is an lvalue reference the result is an lvalue reference, otherwise it is an rvalue reference.

TT&& collapses to
intint&&
int&int& (& && gives &)
int&&int&& (&& && gives &&)

Inside the function, a named parameter is always an lvalue, whatever its declared type. std::forward<T>(x) is essentially static_cast<T&&>(x): if the caller passed an rvalue, T is a non-reference and the cast produces an rvalue again; if the caller passed an lvalue, T is A& and the cast is a no-op. Forgetting it is a silent performance bug, not a compile error:

#include <cstdio>
#include <memory>
#include <string>
#include <utility>

struct Order {
    std::string sym;
    Order(const std::string& s) : sym(s) { std::puts("  copy-constructed string"); }
    Order(std::string&& s) : sym(std::move(s)) { std::puts("  moved string"); }
};

template <class T, class... Args>
std::unique_ptr<T> make_bad(Args&&... args) {   // forgets std::forward
    return std::unique_ptr<T>(new T(args...));    // every named arg is an lvalue
}
template <class T, class... Args>
std::unique_ptr<T> make_good(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

int main() {
    std::string s = "AAPL";
    std::puts("make_bad(temporary):");   make_bad<Order>(std::string("MSFT"));
    std::puts("make_good(temporary):");  make_good<Order>(std::string("MSFT"));
    std::puts("make_good(lvalue s):");   make_good<Order>(s);
    std::printf("s is still \"%s\"\n", s.c_str());
}
make_bad(temporary):
  copy-constructed string
make_good(temporary):
  moved string
make_good(lvalue s):
  copy-constructed string
s is still "AAPL"

make_bad receives a temporary string but passes the named (lvalue) args on, so the copy constructor runs and the string's heap buffer would be allocated and copied. make_good restores the rvalue-ness and the move constructor runs. With the lvalue s, forwarding correctly copies and leaves s intact. Rule: forward a forwarding reference exactly once, at its last use; std::move an rvalue reference.

Worked example

trace std::forward through both calls

For make_good<Order>(std::string("MSFT")) and make_good<Order>(s) with std::string s, state the deduced Args, the parameter type, the type of std::forward<Args>(args), and which Order constructor is chosen.

Show solution

Temporary. The argument is an rvalue of type std::string, so Args = std::string and the parameter is std::string&&. Inside the body, args is a named lvalue. std::forward<std::string>(args) is static_cast<std::string&&>(args), an xvalue (an rvalue), so overload resolution prefers Order(std::string&&): "moved string".

Lvalue s. The argument is an lvalue of type std::string, so Args = std::string& and the parameter is std::string& &&, collapsed to std::string&. std::forward<std::string&>(args) is static_cast<std::string& &&>(args), which collapses to static_cast<std::string&>(args): still an lvalue. Order(std::string&&) cannot bind an lvalue, so Order(const std::string&) is chosen: "copy-constructed string", and s keeps its value.

The information "was it an rvalue?" travels inside the deduced type Args. That is why the call must be std::forward<Args> with the explicit template argument: std::forward cannot deduce it from args, which is an lvalue either way.

Variadic templates and fold expressions

A parameter pack class... Ts matches zero or more types; Ts... xs declares a function parameter pack; sizeof...(Ts) counts it; pattern... expands a pattern once per element. Before C++17, consuming a pack needed recursion (a head-and-tail overload). C++17 fold expressions apply a binary operator across the pack in one line:

FormExpands to (for x1, x2, x3)
(xs op ...) unary rightx1 op (x2 op x3)
(... op xs) unary left(x1 op x2) op x3
(xs op ... op init) binary rightx1 op (x2 op (x3 op init))
(init op ... op xs) binary left((init op x1) op x2) op x3
#include <cstdio>
#include <string>
#include <type_traits>

template <class... Ts>
constexpr auto sum(Ts... xs) { return (xs + ... + 0); }       // binary right fold with init 0

template <class... Ts>
void print_all(const Ts&... xs) {
    ((std::printf("[%s] ", std::to_string(xs).c_str())), ...);  // unary fold over the comma operator
    std::printf("(%zu args)\n", sizeof...(Ts));
}

template <class... Ts>
constexpr bool all_integral = (std::is_integral_v<Ts> && ...);  // empty pack: true

template <class... Ts>
constexpr auto minus_left(Ts... xs) { return (... - xs); }   // ((a - b) - c)
template <class... Ts>
constexpr auto minus_right(Ts... xs) { return (xs - ...); }  // (a - (b - c))

int main() {
    static_assert(sum(1, 2, 3, 4) == 10);
    static_assert(sum() == 0);
    static_assert(all_integral<int, long, char> && !all_integral<int, double> && all_integral<>);
    print_all(1, 2.5, 3L);
    std::printf("left fold %d, right fold %d\n", minus_left(10, 3, 2), minus_right(10, 3, 2));
}
[1] [2.500000] [3] (3 args)
left fold 5, right fold 9

Points worth saying out loud:

  • Direction matters for non-associative operators: (10−3)−2=5(10 - 3) - 2 = 5 but 10−(3−2)=910 - (3 - 2) = 9.
  • A unary fold over an empty pack is an error except for && (gives true), || (false) and the comma operator (void()). Clang rejects (... + x) with an empty pack: "unary fold expression has empty expansion for operator '+' with no fallback value". Use a binary fold with an initial value, as sum does.
  • The comma fold (f(xs), ...) is the idiom for "do something to each argument, left to right". The comma operator guarantees the order; function arguments would not.

SFINAE, and why concepts replaced it

Substitution failure is not an error. When the compiler substitutes deduced arguments into a function template's signature and the result is ill-formed, that template is silently dropped from the overload set instead of causing an error. Before C++20 this was the only way to constrain templates, usually through std::enable_if and the detection idiom (std::void_t):

#include <cstdio>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

// C++11/17 style: detection idiom + enable_if.
template <class T, class = void>
struct has_size : std::false_type {};
template <class T>
struct has_size<T, std::void_t<decltype(std::declval<const T&>().size())>> : std::true_type {};

template <class T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
std::size_t wire_bytes(const T&) { return sizeof(T); }

template <class T, std::enable_if_t<has_size<T>::value, int> = 0>
std::size_t wire_bytes(const T& c) { return 4 + c.size() * sizeof(typename T::value_type); }

// C++20 style: the same two overloads.
template <class T> requires std::is_arithmetic_v<T>
std::size_t wire_bytes20(const T&) { return sizeof(T); }

template <class T> requires requires(const T& c) { c.size(); typename T::value_type; }
std::size_t wire_bytes20(const T& c) { return 4 + c.size() * sizeof(typename T::value_type); }

int main() {
    std::vector<double> v(3);
    std::string s = "AAPL";
    std::printf("%zu %zu %zu\n", wire_bytes(1.0), wire_bytes(v), wire_bytes(s));
    std::printf("%zu %zu %zu\n", wire_bytes20(1.0), wire_bytes20(v), wire_bytes20(s));
}
8 28 8
8 28 8

(wire_bytes(v) is 4+3×8=284 + 3 \times 8 = 28; for the 4-character string it is 4+4×1=84 + 4 \times 1 = 8.) Both versions work. The reasons the language moved on are practical:

  1. Only the immediate context counts. Substitution failure must occur in the declaration itself. An error inside the function body, or inside some other template that the signature instantiates, is a hard error, not a silent removal. Getting this right is why the detection idiom looks so contorted.
  2. Signatures that differ only in a default template argument collide. The intuitive version, template <class T, class = std::enable_if_t<A<T>>> f(T) beside the same with B<T>, declares the same template twice. Clang: "template parameter redefines default argument" and "redefinition of 'f'". That is why the code above uses the uglier std::enable_if_t<..., int> = 0 form.
  3. No ordering. If two enable_if overloads both match, the call is ambiguous. You must make the conditions mutually exclusive by hand (A && !B, B). Concepts have a rule, subsumption, that picks the more constrained overload automatically (next lesson).
  4. Readability and intent. requires std::is_arithmetic_v<T> states the constraint; std::enable_if_t<std::is_arithmetic_v<T>, int> = 0 encodes it as a trick. Concepts can also constrain a non-template member function of a class template, which SFINAE cannot do directly.

Clang's diagnostics for simple enable_if are actually reasonable ("requirement 'std::is_arithmetic_v<Point>' was not satisfied"), but for the requires-expression it goes further and names the failing expression: "because 'c.size()' would be invalid: no member named 'size' in 'Point'".

CRTP: polymorphism resolved at compile time

The curiously recurring template pattern is a base class template that takes the derived class as its parameter: struct Momentum : Strategy<Momentum>. The base can static_cast *this to Derived& and call derived members directly, so there is no vtable, no vptr in the object, and every call can be inlined.

#include <cstdio>
#include <initializer_list>

// Static polymorphism: the base knows the derived type at compile time.
template <class Derived>
struct Strategy {
    double on_tick(double px) {
        double sig = self().signal(px);       // resolved at compile time, inlinable
        ++ticks_;
        return sig;
    }
    long ticks() const { return ticks_; }
private:
    Derived& self() { return static_cast<Derived&>(*this); }
    long ticks_ = 0;
    Strategy() = default;                     // only Derived can construct its base,
    friend Derived;                           // so class B : Strategy<A> fails to compile
};

struct Momentum : Strategy<Momentum> {
    double last = 0;
    double signal(double px) { double s = px - last; last = px; return s; }
};
struct MeanRevert : Strategy<MeanRevert> {
    double mean = 100;
    double signal(double px) { return mean - px; }
};

template <class S>
double run(S& s) {                            // generic driver, no virtual calls
    double pnl_signal = 0;
    for (double px : {100.0, 101.0, 100.5, 102.0}) pnl_signal += s.on_tick(px);
    return pnl_signal;
}

int main() {
    Momentum m; MeanRevert r;
    double a = run(m), b = run(r);  // separate statements: argument evaluation order is unspecified
    std::printf("momentum %.2f after %ld ticks\n", a, m.ticks());
    std::printf("mean-revert %.2f after %ld ticks\n", b, r.ticks());
    std::printf("sizeof(Momentum) = %zu (no vptr)\n", sizeof(Momentum));
}
momentum 102.00 after 4 ticks
mean-revert -3.50 after 4 ticks
sizeof(Momentum) = 16 (no vptr)

Momentum's signals are 100+1−0.5+1.5=102100 + 1 - 0.5 + 1.5 = 102 (the first tick is measured from last = 0); mean reversion gives 0−1−0.5−2=−3.50 - 1 - 0.5 - 2 = -3.5. sizeof(Momentum) is 16: the base's ticks_ and the derived last, 8 bytes each. A virtual version would add an 8-byte vptr.

The private constructor with friend Derived is a guard against the classic copy-paste bug struct B : Strategy<A>, which would static_cast a B to an A: undefined behaviour. With the guard, Clang rejects it: "default constructor of 'B' is implicitly deleted because base class 'Strategy<A>' has an inaccessible default constructor".

Costs to mention: each Strategy<X> is a different, unrelated type, so you cannot keep momentum and mean-reversion strategies in one std::vector<Strategy*> (you need a variant, a type-erased wrapper, or a virtual interface on top); every instantiation adds code; and the pattern is less readable. C++23's "deducing this" (this auto& self) removes the need for the template parameter in many uses, but it is not available in C++20.

Worked example

interview question, virtual or CRTP?

"Our engine runs one strategy per process, chosen at build time, and calls on_tick about a million times a second. A colleague wants to replace the virtual double signal(double) interface with CRTP. Is it worth it, and what would you check?"

Show solution

Reason out loud in three steps.

  1. What a virtual call costs. A load of the vptr, a load of the function pointer from the vtable, and an indirect branch. If one strategy type is used per process, the indirect branch always goes to the same place and the predictor gets it right almost every time, so the call itself costs a few cycles. A million calls a second is roughly one call per microsecond, so the call overhead is a tiny fraction of the budget.
  2. What CRTP actually buys. Not the call, but inlining: once signal is visible at the call site, the compiler can keep state in registers across the loop, vectorise, and propagate constants. That only matters if signal is small and called in a tight loop. If it is a few hundred instructions of feature computation, the gain is noise.
  3. What to check. Measure first, with a benchmark of the real tick loop. Also try the cheap alternative: mark the concrete class final and call through the concrete type, which lets the compiler devirtualise without changing the design (the Object Model lesson shows the generated code). Use CRTP if profiling shows the call boundary blocks optimisation in a hot loop and the strategy set is genuinely fixed at build time. Keep the virtual interface if strategies are chosen at run time or must live in one container.

Knowledge check

Given template <class T> void f(T&& x), what is T for the call f(s) where s is declared as const std::string s?

Knowledge check

A wrapper takes Args&&... args and calls new T(args...) without std::forward. A caller passes a temporary std::string. What happens?

Knowledge check

Which is a genuine limitation of std::enable_if-based SFINAE that C++20 concepts fix?

Key takeaways

  • By-value deduction strips references and top-level const and decays arrays; by-reference keeps const; T&& deduces A& for lvalues and A for rvalues.
  • Reference collapsing: any & wins. std::forward<T>(x) is static_cast<T&&>(x) and restores the caller's value category.
  • Fold expressions replace recursive pack expansion; use a binary fold with an initial value when the pack can be empty, and the comma fold for ordered side effects.
  • SFINAE drops overloads whose signatures fail to substitute; it is fragile (immediate context only, colliding default arguments, no ordering). Prefer requires.
  • CRTP removes virtual dispatch and enables inlining at the cost of one type per strategy and more code; try final first and measure.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).