Skip to content

if constexpr (C++17)

One-Liner

Selectively compiles a branch based on compile-time conditions within templates; discarded branches are not even syntactically checked—a powerful tool for compile-time polymorphism.

None (language feature)

Core API Cheat Sheet

Syntax FormDescription
if constexpr ( condition )Compiles the then branch if condition is true
if constexpr ( condition ) statement else statementCompile-time binary selection
if constexpr chainMulti-branch chain
if constexpr with Conceptsrequires type trait checking
if constexpr with auto(C++20) Concepts overloading is preferred instead

Minimal Example

cpp
template <typename T>
auto get_value(T t) {
    if constexpr (std::is_pointer_v<T>) {
        return *t; // Deduces return type to underlying type
    } else {
        return t;  // Deduces return type to T
    }
}

void usage() {
    int x = 10;
    get_value(x);   // Instantiates with T=int
    get_value(&x);  // Instantiates with T=int*
}

Embedded Applicability: High

  • Zero runtime overhead: conditions are evaluated at compile time, and unmet branches generate no code.
  • Replaces SFINAE and tag dispatching, significantly improving template metaprogramming readability.
  • Ideal for selecting different code paths based on compile-time constants like hardware platforms or peripheral types.
  • Available since C++17; supported by GCC 7+ and ARM Clang 6+.

Compiler Support

GCCClangMSVC
73.919.1

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05