正常
if constexpr (C++17)
In a Nutshell
Inside a template, selectively compile a branch based on a compile-time condition—the discarded branch does not even need to pass syntax checking. A powerful tool for compile-time polymorphism.
Header
None (language feature)
Core API Cheat Sheet
| Syntax Form | Description |
|---|---|
if constexpr (cond) { ... } | Compiles the then branch if cond is true |
if constexpr (cond) { ... } else { ... } | Compiles exactly one of the two branches |
if constexpr (cond1) { ... } else if constexpr (cond2) { ... } else { ... } | Multi-branch chain |
if constexpr combined with concepts | if constexpr (std::integral\<T\>) concept constraint check (std::integral is a concept) |
if constexpr combined with requires | (C++20) Concepts-based overloading is generally preferred instead |
Minimal Example
C++
// Standard: C++17
#include <iostream>
#include <type_traits>
template <typename T>
auto print_type(const T& val) {
if constexpr (std::is_integral_v<T>) {
std::cout << "integral: " << val << "\n";
} else if constexpr (std::is_floating_point_v<T>) {
std::cout << "float: " << val << "\n";
} else {
std::cout << "other\n";
}
}
int main() {
print_type(42); // integral: 42
print_type(3.14); // float: 3.14
print_type("hi"); // other
}Embedded Applicability: High
- Zero runtime overhead: the condition is evaluated at compile time, and branches that do not match generate no code at all
- Replaces SFINAE and tag dispatch, greatly improving the readability of template metaprogramming
- Well suited for choosing different code paths based on compile-time constants such as hardware platform or peripheral type
- Available as of C++17; already supported by GCC 7+ and ARM Clang 6+
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 3.9 | 19.1 |
See Also
Some content is referenced from cppreference.com, used under the CC-BY-SA 4.0 license