【发布时间】:2021-05-29 02:59:52
【问题描述】:
假设我有一个配置函数要由库的用户定义,它可能是也可能不是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() 的值具有不同的行为,但是如果iterations 是,这个函数应该是constexpr,因为我希望用户能够在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() 是constexpr,我可以对algorithm 做些什么来创建函数constexpr?简而言之,我想要像constexpr(constexpr(::iterations())) 这样的东西。
请注意,“有条件的constexpr”通常依赖于模板参数,如Conditionally constexpr member function,在这种情况下可以使用constexpr关键字,但在这种情况下,我希望constexpr是有条件的不是模板参数的东西,而是一个静态已知的函数。将algorithm 标记为constexpr 是compilation error:
error: call to non-'constexpr' function 'bool iterations()'
【问题讨论】:
标签: c++ constexpr c++20 c++-concepts