【问题标题】:How to pass a constexpr array into a function如何将 constexpr 数组传递给函数
【发布时间】:2019-09-24 22:37:39
【问题描述】:

我需要对 constexpr 数组进行检查,但不知道如何将数组传递给检查函数。

#include <cstdlib>

constexpr int is[2] = {23, 42};

void inline check(const int (&elems)[2])
{
    static_assert(elems[0] == 23, "Does not work");
}


void bar()
{
    static_assert (is[0] == 23, "Works");
    check(is);
}

有没有办法在不丢失 constexpr 属性的情况下将数组传递给检查函数?

【问题讨论】:

  • 将其作为模板参数传递。
  • 你甚至不能像普通的int 那样做。 consteval 可能会在一年左右的时间内成为另一个解决方案。

标签: c++ c++11 constexpr


【解决方案1】:

static_assert 内部 check 取决于函数参数。它不会计量您已将 constexpr 参数传递给该函数。 请注意,该函数通常会被多次使用。因此,在一种情况下,static_assert 可能会失败,而另一种情况可能会通过。静态断言不检查从哪里调用包含它的函数。 它必须在编译期间是可验证的,无需检查下面的内容。

可能你需要这样的东西:

constexpr int is[2] = {23, 42};

template<typename T>
constexpr bool firstElementIs23(const T& v)
{
    return v[0] == 23;
}

void bar()
{
    static_assert (firstElementIs23(is), "Works");
}

Live sample

【讨论】:

  • 介绍 T 会让人分心,但你的回答是正确的,干得好
猜你喜欢
  • 2015-11-21
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2012-07-23
  • 2017-06-03
相关资源
最近更新 更多