Skip to content

Commit 0fbde48

Browse files
committed
Support conversion between Spans of compatible types
1 parent 7cbfebb commit 0fbde48

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/span.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,23 @@ class Span
2525
constexpr Span(C* data, std::ptrdiff_t size) noexcept : m_data(data), m_size(size) {}
2626
constexpr Span(C* data, C* end) noexcept : m_data(data), m_size(end - data) {}
2727

28+
/** Implicit conversion of spans between compatible types.
29+
*
30+
* Specifically, if a pointer to an array of type O can be implicitly converted to a pointer to an array of type
31+
* C, then permit implicit conversion of Span<O> to Span<C>. This matches the behavior of the corresponding
32+
* C++20 std::span constructor.
33+
*
34+
* For example this means that a Span<T> can be converted into a Span<const T>.
35+
*/
36+
template <typename O, typename std::enable_if<std::is_convertible<O (*)[], C (*)[]>::value, int>::type = 0>
37+
constexpr Span(const Span<O>& other) noexcept : m_data(other.m_data), m_size(other.m_size) {}
38+
39+
/** Default copy constructor. */
40+
constexpr Span(const Span&) noexcept = default;
41+
42+
/** Default assignment operator. */
43+
Span& operator=(const Span& other) noexcept = default;
44+
2845
constexpr C* data() const noexcept { return m_data; }
2946
constexpr C* begin() const noexcept { return m_data; }
3047
constexpr C* end() const noexcept { return m_data + m_size; }
@@ -44,6 +61,8 @@ class Span
4461
friend constexpr bool operator<=(const Span& a, const Span& b) noexcept { return !(b < a); }
4562
friend constexpr bool operator>(const Span& a, const Span& b) noexcept { return (b < a); }
4663
friend constexpr bool operator>=(const Span& a, const Span& b) noexcept { return !(a < b); }
64+
65+
template <typename O> friend class Span;
4766
};
4867

4968
/** Create a span to a container exposing data() and size().

0 commit comments

Comments
 (0)