How to pass a VLA to a function template?

后端 未结 6 1892
温柔的废话
温柔的废话 2020-12-12 05:00

I have the following code which could not be complied.

using namespace std;
void f(int);
template
void array_ini_1d(T1 (&x)[         


        
6条回答
  •  盖世英雄少女心
    2020-12-12 05:27

    As you use Variable length array (VLA) (compiler extension), compiler cannot deduce N.

    You have to pass it by pointer and give the size:

    template
    void array_ini_1d(T* a, std::size_t n)
    {
        for (std::size_t i = 0; i != n; ++i) {
            a[i] = 0;
        }
    }
    
    void f(int n)
    {
        int arr[n];
        array_ini_1d(arr);
    }
    

    Or use std::vector. (no extension used so). Which seems cleaner:

    template
    void array_ini_1d(std::vector& v)
    {
        for (std::size_t i = 0, size = v.size(); i != n; ++i) {
            a[i] = 0; // or other stuff.
        }
    }
    
    void f(int n)
    {
        std::vector arr(n); // or arr(n, 0).
        array_ini_1d(arr);
    }
    

提交回复
热议问题