上下文
我正在制作一个数学库,我需要使用 sqrt()
。
由于 sqrt()
不是 constexpr
函数,我实现了 constexpr
版本的 sqrt()
和比使用汇编的 std::sqrt()
更快,因此必须在运行时使用。
现在,我使用所有这些来计算 vector 的长度,并且该函数可以是 constexpr,因为我正在结构中实现 constexpr 的一切可能。
constexpr inline Real length() const { return const_sqrt<Real>(lengthSquared());}
如果在非 constexpr 上下文中调用 lenght()
函数,它会在运行时运行,但我有一个更快的运行- sqrt()
的执行时间比 const_sqrt()
的执行时间要长。
问题
如何根据函数是在编译时还是运行时执行来切换使用一种实现或另一种实现。
像这样的事情:
constexpr inline Real length() const { return IN_RUN_TIME ? fast_sqrt<Real>(lengthSquared()) : const_sqrt<Real>(lengthSquared()); }
最佳答案
在 C++20 中,函数 std::is_constant_evaluated
可以用于此目的:
constexpr Real length() const {
return ! std::is_constant_evaluated()
? fast_sqrt(lengthSquared())
: const_sqrt(lengthSquared());
}
据我所知,在c++20之前,没有办法实现这种效果,这就是它被添加到语言中的原因。
另外,请注意 constexpr
意味着 inline
,因此该关键字在这里是多余的。
关于c++ - 如何在 constexpr 函数中实现后备运行时实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62609805/