如何将 VLA 传递给函数模板? [英] How to pass a VLA to a function template?

查看:27
本文介绍了如何将 VLA 传递给函数模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码无法编译.

I have the following code which could not be complied.

using namespace std;
void f(int);
template<typename T1, size_t N>
void array_ini_1d(T1 (&x)[N])
{
  for (int i = 0; i < N; i++)
  {
    x[i] = 0;
  }
}

如果主要内容如下所示,传递数组的正确方法是什么.

What is the proper way to pass the array if the main is something like below.

int main()
{
  int a;
  cin >> a;
  int n = a / 4;
  f(n);
  return 0;
}

void f(int n)
{
  int arr[n];
  array_ini_1d(arr);
}

错误:没有匹配的函数来调用array_ini_1d........

error: no matching function to call to array_ini_1d..............

推荐答案

我认为编译器无法推断出模板中变长数组的大小.另外,在使用之前不要忘记转发声明 f.可变长度数组是 GCC 扩展,您应该收到有关其使用的警告.

I don't think the compiler can deduce the size of a variable-length array in a template. Also, don't forget to forward declare f before you use it. Variable-length arrays are a GCC extension and you should get a warning regarding their use.

这篇关于如何将 VLA 传递给函数模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆