Obtaining a pointer to the end of an array

后端 未结 3 876
走了就别回头了
走了就别回头了 2021-02-02 17:34

I use the following template to obtain a pointer pointing after the last element of an array:

template 
T* end_of(T (&array)[n])
         


        
3条回答
  •  醉酒成梦
    2021-02-02 17:59

    Your proposal is not necessarily evaluated at compile time, it depends on optimisation. The following is calculated at compile time:

    template  char (&array(T(&)[N]))[N];
    
    int main()
    {
      int myArray[10];
    
      std::cout << sizeof array(myArray) << std::endl;
    
      return 0;
    }
    

    It works by creating an array type of char which is the same number of elements as the given array. sizeof always returns size in number of chars.

提交回复
热议问题