相关疑难解决方法(0)

C++20 | std::is_constant_evaluate() 和 const 变量

让我们考虑以下代码:

#include <type_traits>

int foo(int arg) {
    if (std::is_constant_evaluated()) {
        return 1;
    } else {
        return 0;
    }
}  

int main() {
    const auto b = foo(0);
    return b;
}
Run Code Online (Sandbox Code Playgroud)

它用gcc 和 clang返回 0 。我原以为它会返回 1 。

如果foo()是 made constexpr, whileb被简单地保留const,那么它确实返回 1 。

我在这里缺少什么?谢谢!

c++ c++20

3
推荐指数
2
解决办法
137
查看次数

is_constant_evaluated()应该产生constexpr变量吗?

我已经阅读了std::is_constant_evaluated()定义,但是我仍然不确定为什么(1)无法在最新的GCC上运行error: 'x' is not a constant expression

template<auto v>
struct s
{};

constexpr void f(int x)
{
    if (std::is_constant_evaluated())
    {
        // constexpr int z=x; (1)
        // s<x> a; (2)
    }
}

int main(int argc, char* argv[])
{
    f(4);
    //f(argc);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  1. 按照标准,这行得通吗?
  2. 还是仅GCC实施存在问题?
  3. 我如何才能达到预期的行为?基本上是:

随着分支 std::is_constant_evaluated()

  • 如果为真:代码可以将变量用作constexpr(如(2))
  • 如果为假:代码使用变量作为非constexpr

更新

我可以将“解释性”信息“传输”到函数中吗?基本上决定f()是否使用constexprx 进行调用。

UPDATE 关于我要实现的目标的一个更复杂的示例:如果可能,此示例应在编译时对参数进行字符串化。

template<auto v>
struct dummy_stringify
{
    static constexpr auto str=v==4 ? "4" : "31"; // this is just …
Run Code Online (Sandbox Code Playgroud)

c++ constexpr c++20

2
推荐指数
1
解决办法
200
查看次数

C++20。is_constant_evaluate() 与 if constexpr

这是来自 cppreference 的示例:

constexpr double power(double b, int x)
{
if (std::is_constant_evaluated() && !(b == 0.0 && x < 0)) {
    // A constant-evaluation context: Use a constexpr-friendly algorithm.
    if (x == 0)
        return 1.0;
    double r = 1.0, p = x > 0 ? b : 1.0 / b;
    auto u = unsigned(x > 0 ? x : -x);
    while (u != 0) {
        if (u & 1) r *= p;
        u /= 2;
        p *= p;
    }
    return …
Run Code Online (Sandbox Code Playgroud)

c++ c++20

1
推荐指数
1
解决办法
340
查看次数

标签 统计

c++ ×3

c++20 ×3

constexpr ×1