如何通过一个VLA给一个函数模板? [英] How to pass a VLA to a function template?

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

问题描述

我有以下的code这不能被遵守。

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天全站免登陆