I'm new to C++ and I have 2 questions on passing arrays to a function (which may be the same thing).
-
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 ofvoid my_func (const T (&array)[10])? -
What is the difference between a function having an array pointer parameter
void my_func (const T* array)andvoid 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?
没有评论:
发表评论