What is the difference between span and string_view in c++20?

Asked

Viewed 34 times

1

The two classes do basically the same, have a pointer to the first element of the array and the size of the array. I know that string_view is used for character arrays, but could not be used span for the same? I would like to know:

  • Because the redundancy?
  • When I should wear one or the other?

1 answer

2


To the std::basic_string_view, there is a whole set of specific methods to handle strings. std::span is for generic types, including user-defined types.

cppreference for std::basic_string_view:

The class template basic_string_view describes an Object that can refer to Constant contiguous Quence of char-like Objects.

cppreference for std::span:

The class template span describes an Object that can refer to a contiguous Quence of Objects

std::span describes a sequence of objects without citing any in particular. It is a class decorated with a template that receives a type T that will be the type of the object used to create the sequence.

When you "specialize" std::span creating a class by part std::basic_string_view you open up scope to make operations more efficient once the type is known, and implement methods relevant to the specific type.

Obs.: std::basic_string_view is also decorated with a template, but is for the types char, wchar_t, char8_t, char16_t and char32_t.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.