Obtaining a pointer to the end of an array

后端 未结 3 869
走了就别回头了
走了就别回头了 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:46

    You need a const version too. However, as far as I know, there's no actual problems with that approach- I see it used commonly.

    0 讨论(0)
  • 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 <typename T, size_t N> 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.

    0 讨论(0)
  • 2021-02-02 18:07

    The only problem i see is that if you ever don't know the length at compile time, your template won't know what to put in there. So you'd have to say test+x or something anyway, and now you have two different ways to do the same thing.

    Personally i'd rather just use a vector<int> and thus have end() already defined for me. If you ever need the array, it's available as &v[0].

    0 讨论(0)
提交回复
热议问题