Passing 2 dimensional array as argument to function within a for loop

250 Views Asked by At

I am struggling with passing a variable sized 2 dimensional array as parameter to a function. I have been searching the web for this a while but didn't manage to find a solution. When creating two differently sized arrays in forehand, my code works but when i do this with an for loop, this does not work anymore. For the second task, i do use the same variable for the same function. I think the problem becomes crystal clear when looking at the code:

#include <iostream>
using namespace std;

template <typename test>
void func(test& array){
    cout << "it worked." << endl;
}

int main()
{
    
    //commented section works
    //double a1[10][10]; // create 2 differently sized arrays
    //double a2[5][5];
    //func(a1); //execute the function for those 2 differently sized arrays
    //func(a2);

    //uncommented section does not work:
    for(int i; i<2; ++i){
        const int size = 5*(i+1); // variable size
        double a[size][size]; // creating an array with a changing size
        func(a); // executing the function that is supposed to work
    }


    return 0;
}

Error message is:

test.cpp:14:6: note: template argument deduction/substitution failed:

test.cpp:30:9: note: variable-sized array type ‘double [size][size]’ is not >a valid template argument

How can i make the not commented section of the code work? Meaning how can I pass a variable 2 dimensional array to a function within this iteration.

1

There are 1 best solutions below

0
On

As explained in comment, a C-style array with a run-time value isn't standard C++.

If you want a cycle with different sized arrays... if you can use C++20 (so template lambdas)... the best I can imagine pass through two lambdas and with different template sizes transformed in a sequence of template values.

Something as

[]<std::size_t ... Is>(std::index_sequence<Is...>)
 { ([]{ constexpr auto size = 5u*(Is+1u);
        double a[size][size]; 
        func(a); }(), ...); }(std::make_index_sequence<2u>{}); 

Obviously this require that the top value of the cycle is a compile-time known value.

Pre-C++20... I suppose that the first lambda has to be an external template function (should works in C++17 and, with little changes, in C++14; creating a substitute for std::make_index_sequence also in C++11).