What does this C++ code mean?

前端 未结 3 1340
别跟我提以往
别跟我提以往 2020-12-08 10:48

The following code returns the size of a stack-allocated array:

template
int siz(T (&) [size])
{
    return size;
}
         


        
3条回答
  •  余生分开走
    2020-12-08 11:31

    T (&) [size] is a reference to an array. It needs to be a reference because the following program is not legal:

    #include 
    
    int sz(int *) { std::cout << "wtf?" << std::endl; return 0; }
    
    
    int sz(int [4]) { std::cout << "4" << std::endl; return 0; }
    
    int main() {
      int test[4];
      sz(test);
    }
    

    This program fails to compile with:

    test.cc: In function ‘int sz(int*)’:
    test.cc:6:5: error: redefinition of ‘int sz(int*)’
    test.cc:3:5: error: ‘int sz(int*)’ previously defined here
    

    because int sz(int [4]) is identical to int sz(int *).

    The parenthesis are required to disambiguate here because T& [size] looks like an array of references which is otherwise illegal.

    Normally if the parameter wasn't anonymous you would write:

    template
    int sz(T (&arr) [size])
    

    To give the array the name arr. In this instance though all your example code cared about was the deduced size and hence the anonymous argument avoids warnings about unused arguments.

提交回复
热议问题