假设我有一个配置函数要由库的用户定义,它可能是也可能不是 constexpr
。
constexpr int iterations() { return 10; }
// Or maybe:
int iterations() { return std::atoi(std::getenv("ITERATIONS")); }
// I'm okay with requiring the constexpr version to be:
constexpr auto iterations() { return std::integral_constant<int, 10>{}; }
现在我有一个函数,它根据 iterations()
的值有不同的行为,但是这个函数应该是 constexpr
if iterations
是,因为我希望用户能够在 constexpr
中使用它,如果他们将库配置为允许的话:
/*constexpr*/ std::uint32_t algorithm(std::uint32_t x) {
auto const iterations = ::iterations();
// For illustration purposes
for (int i = 0; i < iterations; ++i) {
x *= x;
}
return x;
}
如果 iterations()
是,我可以对 algorithm
做些什么来制作函数 constexpr
?简而言之,我想要类似 constexpr(constexpr(::iterations()))
的东西。
请注意,“条件 constexpr
”通常依赖于模板参数,如 Conditionally constexpr member function在这种情况下,可以只使用 constexpr
关键字,但在这种情况下,我希望 constexpr
以不是的东西为条件模板参数,而是一个静态已知的函数。将 algorithm
标记为 constexpr
是一个 compilation error :
error: call to non-'constexpr' function 'bool iterations()'
最佳答案
您可以通过确保有一些 组模板参数和函数参数来静音编译器诊断,即使::iterations()
对您的函数的调用是常量表达式也是如此。 不是常量表达式。例如:
template <bool True = true>
constexpr std::uint32_t algorithm(std::uint32_t x) {
if constexpr (True) {
auto const iterations = ::iterations();
for (int i = 0; i < iterations; ++i) {
x *= x;
}
return x;
} else {
return 0;
}
}
algorithm<false>(meow)
是常量表达式,只要 meow
是,所以编译器不能提示(https://godbolt.org/z/GvE9ME)。
关于c++ - 非依赖条件的条件 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66390742/