C++ `if constexpr` | Compile-Time Branching in Templates (C++17)

C++ `if constexpr` | Compile-Time Branching in Templates (C++17)

이 글의 핵심

`if constexpr` enables compile-time branching in templates so only the selected branch is instantiated—unlike ordinary `if` inside templates.

What is if constexpr?

Compile-time branching for templates (C++17).

template<typename T>
auto getValue(T value) {
    if constexpr (std::is_pointer_v<T>) {
        return *value;
    } else {
        return value;
    }
}

Basic usage

template<typename T>
void print(T value) {
    if constexpr (std::is_integral_v<T>) {
        std::cout << "integer: " << value << std::endl;
    } else if constexpr (std::is_floating_point_v<T>) {
        std::cout << "float: " << value << std::endl;
    } else {
        std::cout << "other: " << value << std::endl;
    }
}

Examples

Covers: toString style dispatch, variadic print base case with sizeof...(rest), micro-optimization sketches, and replacing SFINAE with if constexpr.

if vs if constexpr

Runtime if instantiates all branches (they must type-check). if constexpr only instantiates the chosen branch.

Pitfalls

  • Condition must be a compile-time context in templates (not a runtime-only value unless in a non-template function with constexpr constants).
  • All branches still parse in some cases—some compilers still diagnose ill-formed code in discarded branches depending on wording; keep branches syntactically valid.
  • Return type: if branches return different types, unify with a common type or explicit return type.

Patterns

Type conversion helpers, container reserve detection with requires, and constexpr size tuning.

FAQ

C++17 feature. No runtime cost for the branch itself—what remains after instantiation is like hand-written code.


  • constexpr lambda
  • CTAD
  • constexpr functions

Keywords

C++, if constexpr, C++17, compile-time, templates.

See also

  • Deduction guides
  • std::any
  • auto deduction