I stumbled upon this http://llvm.org/docs/doxygen/html/classllvm_1_1ArrayRef.html and I am trying to understand what it is supposed to be for.
I cant see what problem ArrayRef
solves, could someone please explain the motivation behind this?
It's the same idea behind std::string_view
: to provide a general view to something, without managing it's lifetime.
In the case of ArrayRef
(which is a terrible name, ArrayView is much better IMHO), it can view other arrays type, including the non-object builtin array (C array). so for example , your function can look like this:
size_t sum (ArrayRef<size_t> view){
return std::accumulate(view.begin(),view.end(),0);
}
and call it with a C-Array:
size_t arr[] = {1,2,3,4,5,6,7};
auto _sum = sum(arr);
if you change the argument type to, for example, std::vector
, ArrayRef
still works.
can you not just template an argument and have that accept any different type of array of any length?
the point is that you don't have to point to the first element, you can point to the 2 ,3 or any element inside the array, so basically your suggested function will look like
template<class Array>
void doSomthing(Array& array , size_t pos, size_t length){/*...*/}
you'de much better with a class in this case (just like you'de better with std::string_view
rather than const char*
+ size_t
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With