I want to write a function that can accept any type of contiguous buffer (e.g. std::array
, std::vector
, raw array, etc) from its call site. I have come up with two methods.
Method #1:
void func( int* const buffer, const std::size_t expectedTokenCount );
Here, expectedTokenCount
is the maximum number of elements that will be inserted into the buffer
.
Method #2:
void func( const std::span<int> buffer, const std::size_t expectedTokenCount );
In this approach, I think that I better write the function in a way that first checks the size of the buffer
via buffer.size( )
and compares it with expectedTokenCount
to make sure that its capacity is greater than or equal to expectedTokenCount
otherwise it throws some kind of exception. Is this a valid and safer method than the 1st method? Which one is better? Will the behavior of span
and its size
member function change if a vector is passed to it or will it be the same as for array?