简体   繁体   中英

cpp static template-dimension pass-as-reference when leading dimension may be zero

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM