C++ constexpr 和 if constexpr

constexpr 和 if constexpr 备忘

constexpr and if constexpr Cheat Sheet

中文

English

1. 概念

1. Concept

- constexpr(C++11引入)用于修饰函数或变量,表示它们可以在编译期计算。

- constexpr (introduced in C++11) marks functions or variables whose values can be evaluated at compile time.

- if constexpr(C++17引入)是编译期条件语句,根据编译期常量条件选择执行分支。

- if constexpr (introduced in C++17) is a compile-time conditional statement that selects branches based on constant expressions.

2. 用途

2. Usage

- constexpr 用于在编译时计算结果,减少运行时开销,提高性能。

- constexpr is used for compile-time computation to reduce runtime overhead and improve performance.

- 用于定义编译期常量,如数组大小、模板参数等。

- Used to define compile-time constants, such as array sizes or template parameters.

- if constexpr 允许根据编译期条件选择代码路径,特别适用于模板元编程。

你可能感兴趣的:(Programming,Practice,c++,开发语言)