Hacker News new | ask | show | jobs
by fluffybucktsnek 4 days ago
You don't have to make function templated to use span. Given:

  void DoSomething(void* p, size_t numBytes);
Presuming p to mean a buffer of bytes, the direct declaration equivalent using span would be:

  void DoSomething(std::span<std::uint_8> /* or std::span<char> */ p);
No templated logic in header files necessary. The only template instantion is std:span, which, in theory, should already be used in most files. The author argues this still makes the code more complex, because of the need of reinterpret_cast, but does it actually?

std::span provides multiple ways of safely accessing data. For one, it provides an contiguous iterator, so you get access to the algorithms library basically for free. Second, you get safer accessors to the data inside, such as at, and even [] can be protected through contracts. Finally, even if you don't care about/can use these features, tying the pointer and length together reduces chances for variable confusion.