由泛型函数设置的数组绑定

Array bound set by a function of a generic

我想将数组长度设置为常数和泛型中的最小值,如下所示:

template <int foo> struct Bar{
  void my_func( int const (&my_array)[std::min(5, foo)] ) { /*...*/ }
};

此代码使用 clang++ 而不是 g++ 编译,我需要我的代码才能同时使用这两种代码。 g++ 给出的错误是:error: array bound is not an integer constant before ']' token。如何将此数组的长度设置为 foo 和 5?

中的最小值

当我使用 clang++ 时,我 运行 遇到了无法将任何内容绑定到 my_array 的问题。我想要 运行 类似的东西:

int main() {
  static const int var[5] = {0,1,2,3,4};
  Bar<5> bar;
  bar.my_func(var);
}

但是当我尝试在 clang++ 中编译这段代码时,我得到:error: reference to type 'const int [*]' could not bind to an lvalue of type 'const int [5]'.

如果我去掉 std::min() 的东西并用 foo 替换它,代码编译并且 运行 没问题。

备注: 要编译此代码,您需要 #include <algorithm> 或类似访问 std::min.

我认为这是模板的一部分并不重要,但是当我尝试使用非模板函数进行类似操作时,例如:

const int const_five = 5;
void new_func( int const (&my_array)[std::min(5,const_five)] ) { /*...*/ }

g++ 说:error: variable or field 'new_func' declared void 和 clang++ 说 candidate function not viable: no known conversion from 'const int [5]' to 'const int [std::min(5, const_five)]' for 1st argument 这两个问题看起来很相似。

保持简单:

[foo < 5 ? foo : 5]

要编译 int const (&my_array)[std::min(5, foo)],您需要一个 std::min 版本,即 constexpr。自 C++14 以来。

检查您使用的 gcc 和 clang 的 -std 默认值(其版本相关)。最终,用 -std=c++14.

编译

由 StoryTeller 提供,nice working MCVE