用于库接口的C风格数组vs std :: array

nbo*_*out 4 c++ arrays

我想编写一个带有提供读取功能的接口的库.C风格的数组容易出错,但允许传递任何大小的缓冲区.C++数组更安全,但强加于大小.

// 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)
Run Code Online (Sandbox Code Playgroud)

我怎样才能拥有两全其美?

我在考虑函数模板,但对于库接口来说似乎并不实用.

template <size_t N>
int read (std::array<std::uint8_t, N>& buf);
Run Code Online (Sandbox Code Playgroud)

编辑 std::vector可能是一个很好的候选人,但如果我们考虑char*并且std::array没有动态分配.

编辑我喜欢很多解决方案gsl::span.我坚持使用C++ 14所以没有std::span.我不知道使用第三个库(gsl)是否会成为问题/允许.

编辑我不认为使用char其他类型可能会对答案产生一些影响,所以更清楚的是操作字节.我char改为std::uint8_t

编辑由于C++ 11保证返回std::vector将被移动而不被复制,因此返回std::vector<std::uint8_t>是可以接受的.

std::vector<std::uint8_t> read();
Run Code Online (Sandbox Code Playgroud)

Hol*_*Cat 6

您可以执行标准库的操作:使用一对迭代器.

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

它为您提供了两全其美的优势:更好的安全性和读入缓冲区任意部分的能力.它还允许您阅读非传统容器.