bremen_matt
bremen_matt

Reputation: 7367

C++ Passing double array via template

I am converting some C-code to C++ so that I can use some more advanced C++ features. However, in one particular function I have a problem because the syntax is allowed in C, but not C++. Specifically, the following is valid C-code, but not C++:

void get_xu_col(int i_start,
                int n,
                double x[n],
                int n_x,
                int n_u,
                int n_col,
                double xu_col[n_col][n_x + n_u]) {
    ...
}

Thanks to the answers here, I understand that this is valid C, but not C++. However, I want to emulate this behavior in C++, and I am not sure of the best way to do that. Specifically, I do NOT want to pass pointers because I would like a compile-time check on the dimensions, which (correct my if I am wrong) C gives me.

The most promising solution, which I see in a lot of places is to switch to a template approach. For example,

template<size_t a, size_t b>
void get_xu_col(int i_start,
                int n,
                double x[n],
                int n_x,
                int n_u,
                int n_col,
                double (&xu_col)[a][b]) {

However, this fails to compile with the puzzling error:

error: no matching function for call to 'get_xu_col'
    get_xu_col(id, n_vars, x, n_x, n_u, n_col, xu_col);
    ^~~~~~~~~~
note: candidate template ignored: could not match 'double' against 'double'

In both the C and C++ versions, I am calling this code like this:

int main(){
    ...
    double xu_col[n_col][n_x + n_u];
    get_xu_col( ..., xu_col );
    ...
}

Can somebody please tell me what that error message is trying to say? Or is there a better idiom for this?

I cannot use the standard library or Boost.

Upvotes: 2

Views: 91

Answers (1)

bremen_matt
bremen_matt

Reputation: 7367

As @StoryTeller points out, the issue is that I forgot a template parameter for the other array being passed. I should have written the template like

template<size_t a, size_t b, size_t c>
void get_xu_col(int i_start,
                int n,
                double (&x)[c],
                int n_x,
                int n_u,
                int n_col,
                double (&xu_col)[a][b]) {

obviously, we could improve this further by dropping some of the parameters being passed since they are identical to the template parameters...

Upvotes: 1

Related Questions