lets say I have a function
auto found = find(first, last, condition);
This find should be able to promise not to modify first to last.
So something like
auto find(const T* first, const T* last, Comp c = less<>);
results in a const T or const T* being returned.
so
int arr[] = {3, 4};
std::vector v(arr, arr +2);
int* found = find(v.begin(), v.end());
** error found is non-const.
I want to modify *found! What are my options? overloads?
You cannot have that signature
int* my_find(const int* begin, const int* end);
(to signaling that your method doesn't modify the range)
without (dangerous) /*const_*/cast.
That signature would allow
const int arr[] = {0, 1, 2, 3};
*my_find(std::cbegin(arr), std::cend(arr)) = 42; // Modifying const object. -> UB
Possibility would be, at the call site, to do all the casting:
// const int* my_find(const int*, const int*);
int arr[] = {0, 1, 2, 3};
auto it = const_cast<int*>(my_find(std::cbegin(arr), std::cend(arr)));
That assumes though that returned pointer is in range, and not pointer on external const object (signatures can't ensure that (Rust has additionally lifetime in type which enforces a little more that assumption :) )).
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