skip to content

Templates and Metaprogramming

Templates generate code per type at compile time, and constexpr, traits and concepts compute and constrain at compile time too. Senior C++ interviews go deep here.

on this pageshow

explore

questions

page 1 of 2

In C++, what is the difference between declaring a variable const and declaring it constexpr?

level: juniorimportance: must knowfreq 68%

answer

  1. read-only versus known while compiling
  2. where the initializer comes from
  3. array bounds and template arguments
  4. the integral const exception

basics

~20 s

A const variable cannot be modified after initialization, but its initializer may run at run time. A constexpr variable is also const and must be initialized by a constant expression, so its value can be used in array bounds, template arguments and static_assert.

solid answer

~40 s

`const` is a promise not to modify: `const int kPort = port_from_env();` is fine, and the value is fixed only once that call has run. `constexpr` on a variable demands that the initializer be a constant expression, makes the variable `const`, and guarantees the value is usable in constant expressions: array bounds, template arguments, `case` labels, `static_assert`. If the initializer is not constant, `constexpr` is a compile error, which is the point: it states intent and has the compiler enforce it. One legacy overlap trips people up: a `const` variable of integral or enumeration type initialized with a constant expression is also usable in constant expressions, while a `const double` is not. For a pointer, `constexpr` applies to the pointer object itself, so `constexpr const char* name` is a constant pointer to `const char`.

code

cpp · 13 lines
cpp
#include <cstdlib>
#include <cstdio>
int port_from_env() { const char* p = std::getenv("PORT"); return p ? std::atoi(p) : 8080; }
const int kMaxPacket = 1500;          // const, constant initializer: usable in constant expressions
const int kPort = port_from_env();    // const, but initialized at run time
constexpr int kHeader = 20;           // must be a constant expression
int main() {
    char buf[kMaxPacket - kHeader];   // OK: both are constant expressions
    static_assert(kHeader == 20);
    // static_assert(kPort == 8080);  // error: kPort is not a constant expression
    // constexpr int p = port_from_env();  // error: non-constexpr function
    std::printf("%zu %d\n", sizeof buf, kPort);
}

go deeper

for a junior

Recall that const means not modified after initialization, while constexpr means the value is known while compiling and the compiler checks it.

for a middle

Explain the integral-const exception, why a const double is not a constant expression, and where constexpr applies on a pointer declaration.

for a senior

Make constexpr the default for protocol constants and tables so the compiler enforces them, and keep const for values computed at startup.

for a principal

Set the team rule: constants are constexpr, with const reserved for run-time values, so a reviewer can tell from the keyword when a value is computed.

## Two different promises C++ has two keywords that look alike on a variable declaration and promise different things: - **`const`** says *this object will not be modified after it is initialized*. It says nothing about **when** the initial value is known. `const int kPort = port_from_env();` reads an environment variable at run time and is perfectly valid. - **`constexpr`** says *the value is known while compiling*. The initializer must be a **constant expression**, the variable is implicitly `const`, and the compiler rejects the declaration if the initializer cannot be evaluated at compile time. The practical difference shows up wherever the language requires a constant: an array bound, a non-type template argument, a `case` label, the condition of `static_assert` or `if constexpr`, an `alignas` argument, an enumerator's value. ## A network stack's constants ```cpp const int kMaxPacket = 1500; // const, constant initializer const int kPort = port_from_env(); // const, initialized at run time constexpr int kHeader = 20; // must be a constant expression char buf[kMaxPacket - kHeader]; // OK static_assert(kPort == 8080); // error ``` With Apple clang 21 the last line fails with `static assertion expression is not an integral constant expression` and the note `initializer of 'kPort' is not a constant expression`. Writing `constexpr int p = port_from_env();` fails earlier, at the declaration: `constexpr variable 'p' must be initialized by a constant expression`, because `port_from_env` is not a `constexpr` function. ## The legacy overlap with const integers Before `constexpr` existed (C++11), C++ already let `const` integers serve as constants, and that rule is still in the standard. A variable is **usable in constant expressions** when it is constant-initialized and either declared `constexpr` or of a `const`-qualified **integral or enumeration** type (or a reference). So: | Declaration | Usable in constant expressions? | |---|---| | `const int kMaxPacket = 1500;` | yes: `const` integral, constant initializer | | `const int kPort = port_from_env();` | no: initializer runs at run time | | `const double kGain = 1.5;` | no: not integral or enumeration | | `constexpr double kGain = 1.5;` | yes | The `const double` row surprises people: `static_assert(kGain > 1.0)` fails with `read of non-constexpr variable 'kGain' is not allowed in a constant expression`. Writing `constexpr` removes the special case: it works for any literal type, including floating-point types, `std::array` and your own classes with `constexpr` constructors. ## Details worth knowing 1. **Pointers.** `constexpr` applies to the declared object. `constexpr const char* kName = "eth0";` is a constant pointer to `const char`; the `const` inside is still needed for the pointee. 2. **Static data members.** A `constexpr` static data member is implicitly `inline` (C++17), so `static constexpr int kMtu = 1500;` in a class needs no out-of-class definition. 3. **Linkage.** At namespace scope, a `const` or `constexpr` variable that is not declared `inline` or `extern` has internal linkage, so each translation unit gets its own copy; the material on linkage covers why that matters. 4. **Types.** The type of a `constexpr` variable must be a **literal type**: roughly, scalars, references, arrays of literal types, and classes with a `constexpr` destructor and at least one usable `constexpr` constructor. ## Mistakes interviewers listen for - **Expecting `const` to mean compile time.** `const auto kTimeout = compute_timeout();` is evaluated at run time; nothing about `const` says otherwise. - **`constexpr` on a function parameter.** A parameter's value comes from the caller, so it can never be declared `constexpr`; Apple clang 21 says `function parameter cannot be constexpr`. To force a compile-time argument, make it a template parameter or call a `consteval` function. - **Assuming a `constexpr` variable inside a loop is recomputed.** Its value is fixed while compiling, whatever the loop does. - **Using `#define` for constants.** A macro has no type and no scope; a `constexpr` variable has both, and the material on macros covers the replacement in detail. ## Which to write Use `constexpr` for every value that is meant to be a compile-time constant: protocol numbers, buffer sizes, lookup tables. The compiler then checks that it really is one, and the value is usable everywhere a constant is required. Use `const` for values that are fixed after initialization but computed at run time, such as configuration read at startup.

  • Why can a const int serve as an array bound but a const double cannot serve in static_assert?
    The standard keeps an old rule: a constant-initialized variable is usable in constant expressions if it is `constexpr` or has `const`-qualified integral or enumeration type. A `const int` initialized with a literal qualifies; a `const double` never does, whatever its initializer. Declaring the double `constexpr` makes it usable.
  • Does constexpr on a pointer variable make the pointed-to data const?
    No. `constexpr` applies to the pointer object itself, making it a constant pointer. `constexpr char* p` would point to modifiable `char`, and is valid only if initialized with a constant address, such as that of a static array. To make the pointee read-only too, write `constexpr const char* p`.

  • const and constexpr are synonyms for variables.
  • A const variable's value is always known at compile time.
  • A const double initialized with a literal can be used in static_assert.
  • constexpr on a pointer makes the pointed-to characters const.
  • constexpr variables may be modified once at startup.
open as a page

Why does a C++ function template defined only in a .cpp file cause an undefined-symbol link error when another file calls it?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A template generates code only when it is instantiated, and the compiler can instantiate it only where the definition is visible. The calling file sees just the declaration, so it references to_bytes<int>, which no object file ever defines.

open as a page

Does a C++ constexpr function always run at compile time, and which contexts force a call to be constant-evaluated?

level: middleimportance: must knowfreq 62%

basics

~20 s

No. A constexpr function may be evaluated at compile time, and must be only where the context requires a constant: a constexpr variable's initializer, a template argument, an array bound, static_assert. Called with run-time arguments, the same function runs at run time.

open as a page

In C++20, how do you define a concept and constrain a function template with it, and what does a caller see on misuse?

level: middleimportance: must knowfreq 60%

basics

~20 s

Write template<class T> concept Name = a bool constraint expression; then apply it with a requires-clause, as a type-constraint such as template<Name T>, or as Name auto in a parameter. A failing call reports which concept was not satisfied.

open as a page

In C++, why does calling template<class T> T larger(T a, T b) as larger(1, 2.0) fail, and how do you fix it?

level: middleimportance: must knowfreq 65%

basics

~20 s

Deduction works out T separately from each argument: int from 1, double from 2.0. The results conflict, and deduction never converts arguments to make them agree. Name T explicitly, convert an argument, or use two type parameters.

open as a page

Where can std::enable_if go in a C++ function template, and why do two overloads differing only in a defaulted enable_if template argument fail to compile?

level: middleimportance: must knowfreq 55%

basics

~20 s

std::enable_if<Cond, T>::type exists only when Cond is true, so it can sit in the return type, an extra parameter or a template parameter. Default template arguments are not part of a template's signature, so two templates differing only there are redeclarations.

open as a page

Why does a C++ serializer branching on std::is_enum_v<T> compile with if constexpr but fail with a plain if?

level: middleimportance: must knowfreq 60%

basics

~20 s

A plain if instantiates every branch for every T, so underlying_type_t<int> or value.size() on an enum is ill-formed. Inside a template, if constexpr (C++17) does not instantiate the discarded branch, so that code need only be valid for types reaching it.

open as a page

How do you sum a C++ parameter pack with a C++17 fold expression, and what happens when the pack is empty?

level: middleimportance: must knowfreq 65%

basics

~20 s

Write (xs + ...) for a unary fold, or (xs + ... + 0) for a binary fold with an initial value. A unary + fold over an empty pack is ill-formed; only &&, || and comma have empty-pack values: true, false, void().

open as a page

In C++, what is the curiously recurring template pattern, and how does its base class call a member of the derived class?

level: juniorimportance: should knowfreq 52%

basics

~20 s

The curiously recurring template pattern (CRTP) is a class deriving from a base template instantiated with itself, as in struct Vec2 : VecOps<Vec2>. The base casts *this to Derived& with static_cast and calls derived members directly, without virtual functions.

open as a page

What does SFINAE mean in C++, and what happens to a function template whose signature fails substitution?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Substitution Failure Is Not An Error: if putting the template arguments into a function template's signature produces an invalid type or expression, that template is silently removed from the overload set instead of stopping the build.

open as a page

In C++, how do you write a full specialization Hasher<std::string> of a class template, and what does it keep from the primary template?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Write template<> struct Hasherstd::string { ... }; after the primary template is declared. It is a completely separate class used whenever the argument is exactly std::string; it inherits no members from the primary, so everything it needs must be redeclared.

open as a page

What does a C++ type trait such as std::is_integral<T> give you, and what are its _v and _t helpers?

level: juniorimportance: should knowfreq 55%

basics

~20 s

A type trait is a class template in <type_traits> that answers a compile-time question about a type: a bool in ::value (is_integral) or a transformed type in ::type (remove_const). The _t alias templates (C++14) and _v variable templates (C++17) shorten both.

open as a page

In C++, what do typename... Ts and Ts... args declare in a variadic log_event template, and what does sizeof...(Ts) return?

level: juniorimportance: should knowfreq 60%

basics

~20 s

typename... Ts declares a template parameter pack of zero or more types; Ts... args declares a function parameter pack with one parameter per type. sizeof...(Ts) is the number of elements in the pack, a compile-time std::size_t, not a size in bytes.

open as a page

Since C++20, what may a C++ constexpr function do during constant evaluation that C++17 rejected, and what still fails?

level: middleimportance: should knowfreq 42%

basics

~20 s

C++20 lets constant evaluation allocate and free memory, so std::vector and std::string work inside it, call virtual functions, and contain try blocks. Still rejected: memory that outlives the evaluation, undefined behaviour, reinterpret_cast, non-constexpr calls and, until C++26, evaluating a throw.

open as a page

What four kinds of requirement can a C++20 requires-expression contain, and why is `requires { sizeof(T) > 4; }` always satisfied?

level: middleimportance: should knowfreq 45%

basics

~20 s

Simple (the expression compiles), type (typename X names a type), compound ({ E } with optional noexcept and -> concept) and nested (requires plus a constant that must be true). sizeof(T) > 4; is simple: it checks validity, never the value.

open as a page

Why does a C++ CRTP instance-counting mixin keep a separate count per derived class, and how can its count go negative?

level: middleimportance: should knowfreq 35%

basics

~20 s

Each InstanceCounter<Derived> is a distinct class, so its static member is a separate variable for every derived type. The count goes negative when the mixin declares only a default constructor: copies use the implicit copy constructor, which never increments, yet their destructors decrement.

open as a page

In C++, what does a CRTP base give up compared with an abstract base class with virtual functions?

level: middleimportance: should knowfreq 48%

basics

~20 s

A CRTP base gives up a common base type: Drawable<Mesh> and Drawable<Sprite> are unrelated, so one container or pointer cannot hold both. Generic code over them must be a template, built once per type, in exchange for no vptr and inlinable calls.

open as a page

How does C++17 class template argument deduction turn Field f("id") into Field<std::string>, and what does a deduction guide add?

level: middleimportance: should knowfreq 50%

basics

~20 s

Since C++17 the compiler deduces a class template's arguments from the initializer by treating each constructor as a function template. A deduction guide adds its own rule, such as Field(const char*) -> Fieldstd::string, which beats the constructor's result.

open as a page

How do you legally specialize std::hash for your own CacheKey type in C++, and which specializations in namespace std are off limits?

level: middleimportance: should knowfreq 55%

basics

~20 s

Adding to namespace std is undefined unless permitted. Specializing a standard class template such as std::hash for your CacheKey is allowed if it meets std::hash's requirements; specializing std function templates, type traits, or std::hash for library-only types is not.

open as a page

A C++ serialize(T&& value) checks std::is_enum_v<T> and misses enums passed as lvalues; why, and should you use std::decay_t or std::remove_cvref_t?

level: middleimportance: should knowfreq 45%

basics

~20 s

For an lvalue argument a forwarding reference deduces T as Kind& or const Kind&, and is_enum_v of a reference type is false. Strip it first: remove_cvref_t (C++20) removes only reference and cv; decay_t also turns arrays and functions into pointers.

open as a page

In C++, what is the difference between total(square(xs)...) and square(total(xs...)), and where else can a pack expansion appear?

level: middleimportance: should knowfreq 45%

basics

~20 s

The ellipsis repeats the whole pattern to its left. total(square(xs)...) squares each element and passes the results to total; square(total(xs...)) passes every element to one total call. Expansions also appear in base lists, member initializers and braced initializers.

open as a page

When would you declare a C++20 function consteval rather than constexpr, and what does C++23's if consteval add?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Use consteval when a call must never happen at run time, such as validating a configuration or format string: every call must produce a constant, or the build fails. C++23's if consteval lets a constexpr function call it in its compile-time branch.

open as a page

In C++20, what does constinit guarantee for a global or thread_local variable, and how does it differ from constexpr?

level: seniorimportance: should knowfreq 32%

basics

~20 s

constinit (C++20) requires a variable with static or thread storage duration to be initialized at compile time, or the program is ill-formed, but leaves it mutable. constexpr also requires a constant initializer, makes the variable const and usable in constant expressions.

open as a page

Two C++20 overloads constrained by `requires std::is_arithmetic_v<T>` and `requires std::is_arithmetic_v<T> && std::is_integral_v<T>` are ambiguous for int; why, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Subsumption compares atomic constraints by identity, meaning the same expression from the same place in the source. Two separately written is_arithmetic_v<T> are different atomic constraints, so neither overload subsumes the other. Name the predicate as a concept and build the stricter one from it.

open as a page

How does a C++23 explicit object parameter (deducing this) replace CRTP, and where does it behave differently from it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

In C++23 a member function template can take its object as a deduced parameter, template <class Self> auto f(this Self&& self), so Self becomes the derived type with no template base. Unlike CRTP, it follows the static type at each call.

open as a page

A C++ class Feet mistakenly derives from Printable<Meters>, and its print() outputs garbage; why does it compile, and how do you make the CRTP base reject it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Printable<Meters> is a valid base for any class, and static_cast<const Meters&>(*this) is unchecked, so reading a Feet as a Meters is undefined behaviour. Making the base's constructor private and declaring friend Derived turns the slip into a compile error.

open as a page

In a C++ class template deriving from WriterBase<T>, why does an unqualified write_raw() call fail, and when do you need typename and template?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Templates look up names in two phases. The non-dependent call write_raw() is bound at definition, when the dependent base WriterBase<T> is not searched. Write this->write_raw(); add typename for dependent types and template before dependent member templates.

open as a page

A C++ to_string overload names a helper struct's nested type in its return type, and an unsupported argument causes a hard error instead of SFINAE; why?

level: seniorimportance: should knowfreq 35%

basics

~20 s

SFINAE covers only the immediate context: the types and expressions written in the signature. Naming the helper's nested type instantiates the helper class, and an error inside that class's definition happens in a separate instantiation, so it is fatal.

open as a page

How does the std::void_t idiom detect whether a C++ type has a str() member, and why must the primary template's second parameter default to void?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A partial specialization takes std::void_t<decltype(std::declval<const T&>().str())> as its second argument: if the expression is valid it becomes void, matches the primary's default, and the true specialization wins; otherwise it drops out. Any other default never matches.

open as a page

Why can't you partially specialize a C++ function template like hash_value<T*>, and why does overloading usually beat full specialization for function templates?

level: seniorimportance: should knowfreq 45%

basics

~20 s

C++ forbids partial specialization of function templates; overloading does that job. A full specialization takes no part in overload resolution: the compiler picks a primary template first and only then uses its specializations, so one can be silently bypassed.

open as a page

showing 1–30 of 36