HarryLeong
HarryLeong

Reputation: 323

Why doesn't std::vector<T> have conversion operator std::span<T,extent>?

Considering the std::string has (conversion operator) operator std::string_view, Why doesn't std::vector<T> have operator std::span<T,extent>?

What is the underlying reason? Is the operator std::span<T,extent> hamful?

Edit: Thanks to NathanOliver. The following code indeed can work

void foo(std::span<int> f);
std::vector<int> data;
foo(data);

I'm still confused about which form is better? conversion operator or constructor? std::string and std::string_view show us an example of a conversion operator. std::vector and std::span (initially named array_view?) show us an example of the constructor.

Upvotes: 1

Views: 1676

Answers (1)

NathanOliver
NathanOliver

Reputation: 180720

There is no need for a std::vector<T>::operator std::span<T,extent> because std::span has the constructor

template< class R >
explicit(extent != std::dynamic_extent)
constexpr span( R&& r );

Which accepts a std::vector. Here R basically needs to be a contiguous range like object. For full details on the constraints see constructor 7 here

You can see your code working in this live example

Upvotes: 1

Related Questions