2021年4月25日星期日

Passing an array to function without explicit array size

I'm new to C++ and I have 2 questions on passing arrays to a function (which may be the same thing).

  1. When passing an array to a function by reference, doesn't parameter require explicit size information as in void my_func (const T &array) instead of void my_func (const T (&array)[10])?

  2. What is the difference between a function having an array pointer parameter void my_func (const T* array) and void my_func (const T(* array)[10])(with or without explicit array size)?

Below is the code which accepts any size of array without explicitly passing array size:

template<typename _Ret, //return type           typename _Coll> //collection type, no size argument  _Ret Sum(const _Coll& c) {            _Ret sum = 0;          for (auto& v : c)                  sum += v;          return sum;  }    int main() {          // With regular array, Passed as reference          int arr[] = {1, 2, 3, 4, 5};          std::cout << Sum<int64_t>(arr) << "\n"; //15            // With vector           std::vector<int> vec = {1, 2, 3, 4, 5};          std::cout << Sum<int64_t>(vec) << "\n"; //15          return 0;  }    

The article from which this example originates says as below:

Additionally, the use of templates can even avoid the unsightly array reference syntax and make the code work for any array size.

If this works, then is the general template for any array size as below unnecessary?

template<typename T, std::size_t S>  void my_func(T (&arr)[S]) {          ... ...;  }  

And also a side question, why doestemplate<typename _Ret, typename _Coll> requires 2 template arguments but Sum<int64_t>(arr) specifies only 1 template argument?

https://stackoverflow.com/questions/67260487/passing-an-array-to-function-without-explicit-array-size April 26, 2021 at 11:27AM

没有评论:

发表评论