r/cpp_questions • u/Expert_Sheepherder24 • 1d ago
OPEN C++26 template for loop std::span<T,N>
Hi, C++26 added "template for" operator , https://cppreference.com/cpp/language/template_for .
GCC 16.2 it supported. It works with std::tuple, std::array, but can't compile with std::span<T,N> fixed size.
How to achieve that, std::span<T,N> also worked with "template for" ?
https://godbolt.org/z/6s9MfzTeb
It be very useful for hand-by unroll loop.
I try specialize std::tuple_size, std::tuple_element, std::get for std::span<T,N> , but it don't helped.
3
u/IyeOnline 1d ago
If you mark sp as constexpr static it compiles.
To me, that suggests that this is a compiler bug/limitation, but I have not read the wording on template for.
1
u/TotaIIyHuman 1d ago
constexpr std::span<const int, 3> sp{arr};
static constexpr auto seq{std::make_index_sequence<3>{}};
template for (auto x : seq)
std::println("{}", sp[x]);
3
u/SyntheticDuckFlavour 1d ago
As far as I can tell, this is only possible if the span itself is a constant expression. It needs to view a static storage of
constexprdata.