Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C-style array vs std::array for library interface

Tags:

c++

arrays

I want to write a library with an interface that provide a read function. C-style array is error prone but allow to pass a buffer of any size. C++ array are safer but impose to be constructed with a size.

// interface.h

// C-style array
int read (std::uint8_t* buf, size_t len);

// C++ array
int read (std::array<std::uint8_t, 16>& buff)

How can I have the best of both worlds?

I was thinking about function template but it does not seems practical for a library interface.

template <size_t N>
int read (std::array<std::uint8_t, N>& buf);

EDIT std::vector could be a good candidate but if we consider that char* and std::array do not have dynamic allocation.

EDIT I like a lot the solution with gsl::span. I am stuck with C++14 so no std::span. I don't know if using a third library (gsl) will be an issue/allow.

EDIT I did not think that using char over another type could have some influence on the answer, so to be clearer it is to manipulate bytes. I change char to std::uint8_t

EDIT Since C++11 guarantee that a return std::vector will moved and not copied, returning std::vector<std::uint8_t> is acceptable.

std::vector<std::uint8_t> read();
like image 791
nbout Avatar asked Mar 07 '23 21:03

nbout


1 Answers

You could do what the standard library does: Use a pair of iterators.

template <typename Iter> int read(Iter begin, Iter end)
{
    // Some static assets to make sure `Iter` is actually a proper iterator type
}

It gives you the best of both worlds: Slightly better safety and ability to read into an arbitrary part of a buffer. Also it allows you to read into non-continguous containers.

like image 166
HolyBlackCat Avatar answered Mar 16 '23 21:03

HolyBlackCat