在编译期间或运行时确定“constexpr”的执行
Determine `constexpr` execution - during compilation or at runtime?
有没有办法在编译阶段和运行时实现constexpr
函数的不同行为?
考虑以下示例(使用D: static if
的理论特征):
constexpr int pow( int base , int exp ) noexcept
{
static if( std::evaluated_during_translation() ) {
auto result = 1;
for( int i = 0 ; i < exp ; i++ )
result *= base;
return result;
} else { // std::evaluated_during_runtime()
return std::pow( base , exp );
}
}
如果没有,是否有办法将constexpr
限制为仅在编译时?
不,没有这样的方法。
对不起。
N3583是一篇建议进行更改以满足您的要求的论文。
在C++20之前,这是不可能的。C++20然后添加了std::is_constant_evaluated
,这正是用于这个用例的:
constexpr int pow(int base, int exp) noexcept
{
if (std::is_constant_evaluated())
{
auto result = 1;
for (int i = 0; i < exp; i++)
result *= base;
return result;
}
else
{
return std::pow(base, exp);
}
}
请注意,if
语句本身是而不是constexpr
。如果是,那么整个else arm将从函数中删除,并且它将始终运行If arm,无论是在编译时还是在运行时。对于一个普通的if语句,基本上可以得到两个函数。在编译时运行的
constexpr int pow(int base, int exp) noexcept
{
auto result = 1;
for (int i = 0; i < exp; i++)
result *= base;
return result;
}
一个在运行时被编译并运行的:
constexpr int pow(int base, int exp) noexcept
{
return std::pow(base, exp);
}
编译器可以安全地删除if arm,因为它可以证明它在运行时是不可访问的。相当整洁。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 多成员Constexpr结构初始化
- 执行函数时导致崩溃的变量
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- 在C++中对T*类型执行std::move的意外行为
- Visual C++ constexpr Hints
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在编译期间或运行时确定“constexpr”的执行
- 检测 constexpr 函数的执行时间
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- 强制执行编译时constexpr
- 如何在constexpr函数中执行运行时断言?