
Recall first from Function templates and class templates
- Template argument deduction matches argument types against parameter patterns without implicit conversions; explicit template arguments re-enable conversions
- A deduced T&& is a forwarding reference: an lvalue argument makes T an lvalue reference and reference collapsing keeps the parameter an lvalue reference
- Class template member functions are instantiated only when used; an explicit instantiation definition generates every member
Two-phase lookup: what is checked when
6 min readThe previous lesson wrote templates and let the compiler deduce their arguments. This lesson looks inside instantiation: two-phase lookup, the typename and template disambiguators, non-type parameters, and full and partial specialization.
Here is a real problem you will meet with GCC 13 on Ubuntu 24.04: a template in a header fails to compile even though no code ever calls it. Or the reverse: a template compiles for months, then a colleague instantiates it with a new type and a wall of errors appears pointing at code nobody touched. Both behaviours follow from one rule. A the compiler generating concrete code from a template by substituting a specific set of template arguments is not the first time the compiler looks at the template. It is the second.
The C++ standard splits the work into two phases. In phase one, at the point where the template is defined, the compiler parses the template and checks everything that does not depend on the template parameters. In phase two, at each point of instantiation, it substitutes the actual arguments and checks everything that does depend on them. The dividing line is the a name whose meaning depends on a template parameter, so it cannot be resolved until the arguments are known. A name like std::cout or a global variable is non-dependent: its meaning is fixed, so it is looked up and bound in phase one. An expression like v * 2, where v has the parameter type T, is dependent: whether the multiplication is even legal depends on what T turns out to be, so it is checked in phase two.
Watch what this means for a non-dependent name:
template <typename T>
T twice(T v) {
return v * scale_factor; // non-dependent: looked up right here
}
int scale_factor = 2; // declared too late
GCC rejects this at the definition, before any instantiation, with error: 'scale_factor' was not declared in this scope. It does not matter that twice is never called: phase one binds scale_factor using ordinary lookup at the definition point, and lookup finds nothing. Moving the declaration above the template fixes it, and the template then binds to that specific variable permanently. Declaring another scale_factor later, or one in the caller's namespace, changes nothing: non-dependent names do not get a second chance.
Dependent expressions behave the opposite way:
template <typename T>
auto area(T shape) {
return shape.area(); // dependent: checked at instantiation
}
Nothing is known about T at the definition, so shape.area() is only checked when you call area with a concrete type. If that type has no area() member, the error appears at instantiation, and GCC's diagnostic shows the substitution that failed. For dependent function calls, phase two also uses argument-dependent lookup (ADL): the namespaces associated with the argument types are searched at the point of instantiation, which is how std::swap-style customization points work.
Phase 1, at the definition: parse the template, check syntax, and bind every non-dependent name with ordinary lookup at this point.
Reject early: an unknown non-dependent name is an error now, even if the template is never used.
Phase 2, at each instantiation: substitute the template arguments into dependent expressions and check them against the real types.
Dependent calls: run lookup again, including ADL in the namespaces of the argument types.
Emit code: each distinct set of arguments produces its own function or class, visible as its own symbol in the object file.
Two keywords exist purely to help phase one parse dependent constructs. The first is typename. Inside a template, a qualified name like C::value_type is dependent when C is a parameter, and the compiler cannot know whether it names a type or a static member. The rule: it is assumed to name a value unless you say otherwise.
template <typename C>
typename C::value_type first(const C& c) {
typename C::value_type tmp = *c.begin(); // typename marks a type
return tmp;
}
Leave out the typename on the local variable and GCC says error: need 'typename' before 'C::value_type' because 'C' is a dependent scope. The keyword is your promise that the name is a type; phase two verifies the promise against the actual argument. Since C++20 (P0634) the typename in the return type above is optional, and GCC 13 accepts C::value_type first(const C& c) with -std=c++20; inside a function body it is still required.
The second keyword is template, used as a disambiguator when you call a member template through a dependent expression:
template <typename T>
void use(T obj) {
obj.template get<int>(); // get is a member template of T
}
Without the .template marker, phase one parses < as the less-than operator, because it does not yet know that get is a template. The marker says: what follows is a template argument list, not a comparison. You need it only in dependent contexts; on a concrete object, plain obj.get<int>() is fine.
Instantiation also has a visible footprint. Implicit instantiation is lazy: only what the program uses gets generated, and for class templates only the member functions you actually call get their bodies instantiated. Compile with g++ -Wall -Wextra -std=c++20 -c twice.cpp -o twice.o and inspect the result with nm -C twice.o: each used instantiation appears as its own weak symbol (marked W), such as int twice<int>(int). Weak means the linker keeps one copy when several object files contain the same instantiation. The c++filt tool demangles a single symbol if you have one copied from raw nm output. No instantiation, no symbol: an unused template contributes nothing to the binary.
Non-type template parameters: values as arguments
3 min readEverything so far used type parameters. A a template parameter that takes a constant value (an integer, a pointer, or since C++20 a structural class value) instead of a type, usually written NTTP, lets you pass a number or other constant into the type system. The classic embedded use is a fixed-capacity buffer:
#include <cstddef>
template <typename T, std::size_t N>
class RingBuffer {
T data_[N];
public:
static constexpr std::size_t capacity = N;
};
RingBuffer<int, 64> rx; // storage for 64 ints, no heap
RingBuffer<int, 128> tx; // a different, unrelated type
N is part of the type. RingBuffer<int, 64> and RingBuffer<int, 128> are as unrelated as int and double: you cannot assign one to the other, and a function taking one will not accept the other. The size lives in the type, so the array is laid out inside the object, capacity is usable in constant expressions, and nothing is allocated at run time. This is the foundation of the no-heap designs later in this module.
The argument for an NTTP must be a constant expression. A literal like 64, a constexpr variable, or sizeof of something all work. A plain run-time variable does not: std::size_t n = read_config(); RingBuffer<int, n> b; is rejected, because the compiler must know the layout of b at compile time. That is the whole trade: you give up run-time flexibility and get a type the compiler can fully check and lay out.
Before C++20, NTTPs were limited to integral and enumeration types, pointers, references, and std::nullptr_t. C++17 added template <auto N>, which deduces the parameter's type from the argument, so one template can accept 5 or 'x' without you spelling out the type. Floating-point values were not allowed before C++20. C++20 allows them: GCC 13 with -std=c++20 accepts template <double D> (checked), while a C++17 build rejects it.
C++20 widened NTTPs to class types, with a strict condition: the class must be a a class whose bases and non-static data members are all public, non-mutable, and themselves structural types (or arrays of them). Roughly: a class that is nothing but public, fixed data, with no private state and no inheritance tricks. The reason is that two template arguments of class type count as the same argument when their corresponding member values are equal, so the compiler must be able to compare them member by member. A small fixed string qualifies:
struct FixedString {
char data[8]{};
constexpr FixedString(const char* s) {
for (int i = 0; i < 7 && s[i]; ++i)
data[i] = s[i];
}
};
template <FixedString Name>
struct Channel {
static constexpr const char* name = Name.data;
};
static_assert(Channel<"uart0">::name[0] == 'u');
The constructor is constexpr, the only member is a public array, and the string literal "uart0" is converted to a FixedString at compile time. Channel<"uart0"> and Channel<"spi1"> are different types, each carrying its name as compile-time data: useful for naming log channels, device paths, or register blocks without storing a run-time string. Two FixedString arguments with the same characters are the same argument, so Channel<"uart0"> written in two files is one type, not two.
Before C++20, template <double Scale> is ill-formed. With -std=c++20, GCC 13 accepts it. Code that must also build as C++17 should pass integers instead, for example a numerator and a denominator, and compute the ratio inside the template.
Full and partial specialization
5 min readSometimes the generic definition is wrong or wasteful for one specific argument. A an alternative definition of a template for one completely fixed set of template arguments, written with template<> and no remaining parameters handles that case:
template <typename T>
struct Storage { static constexpr const char* tag = "primary"; };
template <>
struct Storage<bool> { static constexpr const char* tag = "bool"; };
template <> with Storage<bool> says: when the argument is exactly bool, use this definition instead. Two rules matter. First, a full specialization is a complete, independent definition: nothing is inherited from the primary template, so if the primary has ten members and your specialization defines one, the other nine simply do not exist for that argument. Second, the specialization must be declared before the first use that would instantiate Storage<bool> in every translation unit; using it first and specializing later is an ill-formed program that compilers are not required to diagnose. In practice: put specializations in the same header, right after the primary template.
A an alternative definition that still has template parameters, matching a family of argument patterns such as all pointer types covers a pattern rather than one fixed argument:
template <typename T>
struct Storage<T*> { static constexpr const char* tag = "pointer"; };
This matches Storage<int*>, Storage<bool*>, Storage<Widget*>: any pointer. You can also match shapes like T[N] for arrays, or T (*)(Args...) for function pointers. Partial specialization exists only for class templates (and variable templates). Function templates can be fully specialized but not partially; for functions, write an overload instead, which is almost always what you want anyway.
When you write Storage<X>, the compiler selects in a fixed order: an exact full specialization wins outright; otherwise it collects the partial specializations whose patterns match and picks the most specialized one; if none match, the primary template is used. With the three definitions above:
Storage<int>::tag; // "primary": no specialization matches
Storage<int*>::tag; // "pointer": the partial matches
Storage<bool>::tag; // "bool": the full specialization wins
Storage<bool*>::tag; // "pointer": the full spec matches bool only
The last line is the one people get wrong: Storage<bool> and Storage<bool*> are different arguments, and the full specialization for bool says nothing about pointers to bool. If two partial specializations match and neither is more specialized than the other, the use is ambiguous and the compiler rejects it.
Going deeperCompile-time recursion and integral_constant
Specialization plus instantiation gives you a working compile-time computation engine, the technique called template metaprogramming. A recursive template refers to itself with a smaller argument, and a full specialization stops the recursion:
template <unsigned N>
struct Factorial {
static constexpr unsigned value = N * Factorial<N - 1>::value;
};
template <>
struct Factorial<0> { static constexpr unsigned value = 1; };
static_assert(Factorial<5>::value == 120);
Reading Factorial<5>::value forces the compiler to instantiate Factorial<4>, then Factorial<3>, down to the full specialization at 0. The recursion happens entirely inside the compiler; the program contains only the constant 120. There is a safety limit: GCC caps recursive instantiation depth with -ftemplate-depth (default 900), so a missing base case produces a depth-exceeded error rather than a hung compiler.
The standard library's type traits are built on this machinery, anchored by std::integral_constant, whose core is exactly an NTTP wrapped in a type:
template <class T, T v>
struct integral_constant {
static constexpr T value = v;
using value_type = T;
using type = integral_constant;
};
using true_type = integral_constant<bool, true>;
using false_type = integral_constant<bool, false>;
A trait like std::is_same<A, B> inherits from true_type or false_type, chosen by partial specialization, so a compile-time question becomes a type you can branch on. Modern constexpr functions (a later lesson) compute the same values with ordinary syntax, but the trait pattern still runs the standard library, and reading it requires exactly the tools of this lesson.
You now know what the compiler checks at each phase, how to pass compile-time values and structural class values as arguments, and how specialization redirects a template to a different definition. The next lesson, "Variadic templates and compile-time selection", answers the natural follow-up: what if a template must accept any number of arguments, and how does the code select between alternatives at compile time?
Key takeaways
- Non-dependent names are bound at the template definition, so an unknown one is an error even if the template is never instantiated.
- A dependent qualified name is assumed to name a value unless typename marks it as a type.
- Non-type template arguments must be constant expressions; C++20 also allows structural class types and floating-point values.
- An exact full specialization beats every partial specialization, and the most specialized matching partial specialization beats the primary template.
Reflect
- Explain to a colleague, in two sentences: predict whether a name inside a template is checked at definition or at instantiation
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagegcc(1): the GNU compiler driver
- Man pagenm(1): list symbols from object files
- Man pagec++filt(1): demangle C++ symbols
Official documentation first. Links checked when the lesson was published.