正常
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.
Header
None (language feature)
Core API Cheat Sheet
| Syntax Form | Description |
|---|---|
if constexpr ( condition ) | Compiles the then branch if condition is true |
if constexpr ( condition ) statement else statement | Compile-time binary selection |
if constexpr chain | Multi-branch chain |
if constexpr with Concepts | requires 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
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 3.9 | 19.1 |
See Also
Part of the content references cppreference.com, licensed under CC-BY-SA 4.0