Since ranges::view_interface
has an explicit operator bool()
function, this makes most C++20 ranges adaptors have the ability to convert to bool
:
https://godbolt.org/z/ccbPrG51c
static_assert(views::iota(0));
static_assert("hello"sv | views::split(' '));
static_assert(views::single(0) | std::views::transform([](auto) { return 0; }));
Although this seems very convenient, do we really need this feature? The reason is that traditional STL containers such as std::vector
, or commonly used views such as std::string_view
, do not have this functionality of converting to bool
, which seems to have some inconsistencies. And it seems more intuitive to just call .empty()
or ranges::empty
directly to determine whether a range is empty.
In addition, this implicit conversion maybe also causes confusion:
static_assert(!views::empty<int>);
So, why does ranges::view_interface
provide this operator bool
function? Are there any practical use cases?
Please note that this may be an opinion-based question, but I want to know the philosophy behind view_interface
providing operator bool
.
From this blog post by Eric Niebler, whose range-V3 library heavily influenced C++20 ranges
... custom view types can inher[i]t from
view_interface
to get a host of useful member functions, like.front()
,.back()
,.empty()
,.size()
,.operator[]
, and even an explicit conversion tobool
so that view types can be used in if statements// Boolean conversion operator comes from view_interface: if ( auto evens = vec | view::filter(is_even) ) { // yup, we have some evens. Do something. }
So this is at least one use case for converting a range view to bool
. Note that this is an explicit conversion, so it only happens in a context that performs the conversion, e.g. by casting explicitly, or using it in an if
condition, or in a static_assert
as you have in your question.
As mentioned by Eric on a comment on this answer, this feature is not actually useful any longer for the stated use case, presumably since we now have if-with-initializers as a language construct, and so this feature could be deprecated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With