Home > Back-end >  cpp static template-dimension pass-as-reference when leading dimension may be zero
cpp static template-dimension pass-as-reference when leading dimension may be zero

Time:01-30

I have the following function.

template<int m, int n>
void foo(float (&A)[m][n]){}

int main(){
    float x[3][4], y[0][4];
    
    foo<3,4>(x);
    //if(false){ foo<0,4>(y); } // POSITION 1
}

When I incomment POSITION 1, then the following error is thrown:

$ g   minimum_example.cpp

.\minimum_example.cpp: In function 'int main()':
.\minimum_example.cpp:10:13: error: no matching function for call to 'foo<0, 4>(float [0][4])'
   10 |     foo<0,4>(y);
      |     ~~~~~~~~^~~
.\minimum_example.cpp:3:6: note: candidate: 'template<int m, int n> void foo(float (&)[m][n])'
    3 | void foo(float (&A)[m][n]){}
      |      ^~~
.\minimum_example.cpp:3:6: note:   template argument deduction/substitution failed:

$

The issue is that I cannot catch the exception m==0 at compile time. Preferably, I am interested in a solution that does not change the call syntax from POV of main.

CodePudding user response:

The answer is as follows:

template<int m, int n>
void foo(float A[m][n]){}

int main(){
    float x[3][4], y[0][4];
    
    foo<3,4>(x);
    //if(false){ foo<0,4>(y); } // POSITION 1
}

That is, you just replace (&A) with A in line 2.

Reasons are:

  • Violation of standard is of no practical relevance in this matter because the code does in GCC and CLANG exactly what it is supposed to do.
  • A reference cannot be passed explicitly because a reference to a NULL array cannot be generated (therefore the compilation error).
  • The (&A) can be replaced with A because when $m>0$ the notation A[m][n] passes A as reference.
  • Related