Reputation: 789
I am aware that a regular, built-in array can be passed in to a function with variable sizes. However, is there a good technique to be able to write a single function that takes an array class object reference, but the size can be variable?
Is there a template technique for doing this? Or do we just use vectors instead?
Thanks!
~ G
UPDATE:
Clarification - I'm speaking of the std::array
class in <array>
library. When you create an instance of the class, it has two template parameters: array<type, size>
.
Upvotes: 0
Views: 1222
Reputation: 596948
I am aware that a regular, built-in array can be passed in to a function with variable sizes.
No, it can't. It can only be passed in by-pointer or by-reference. In the case of by-pointer, all size information is lost. In the case of by-reference, the size has to be stated explicitly in the parameter itself as part of its type, thus you can't pass separate arrays of different sizes to the same function.
However, is there a good technique to be able to write a single function that takes an array class object reference, but the size can be variable?
Yes, use a template for the size, eg:
template<typename T, size_t N>
void doSomething(T (&arr)[N])
{
// use arr up to N elements as needed...
}
int arr1[5];
doSomething(arr1);
char arr2[10];
doSomething(arr2);
...
UPDATE: in the case of std::array
, the template approach still works, eg:
template<typename T, size_t N>
void doSomething(std::array<T, N> &arr) {
// use arr up to N elements as needed...
}
std::array<int, 5> arr1;
doSomething(arr1);
std::array<char, 10> arr2;
doSomething(arr2);
...
Upvotes: 3
Reputation: 238401
Is there a template technique for doing this?
Yes. The technique is: Use a template.
Example:
template<class Array>
void function(const Array&);
Note that templates are a compile time entities and the size cannot be variable at runtime.
Or do we just use vectors instead?
For arrays with runtime bound: Yes.
Upvotes: 1