c++ - 非依赖条件的条件 constexpr

标签 c++ constexpr c++20 c++-concepts

假设我有一个配置函数要由库的用户定义,它可能是也可能不是 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/

相关文章:

c++ - 不同的 constexpr 行为 vs2015u2 vs gcc

c++ - 使用不支持的类型继承 C++ 中的模板类

c++ - constexpr 函数参数作为模板参数

c++ - 如何将模板化固定字符串传递给另一个类的构造函数的重载

c++ - 比较 C++20 中的多态类型

c++ - C++ 中的非法间接寻址

c# - 在 C# 或 C++ 中搜索另一个音频中的音频

c++ - 具有折叠表达式的函数的乘积

c++ - 为什么我不能在函数中使用 constexpr 值,但我可以在这个值的范围内做同样的事情?

c++ - ranges::views 如何实现 O(1) 复杂度?