Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can std::ranges work with initializer_list?

I wonder if the std::ranges::* algorithms should be working with std::initializer_list. For example, line (B) in the following snippet compiles while line (A) does not, when compiling with x64 MSVC v19.latest and option /std:c++latest (godbolt.org/z/5oTEz1q5P).

#include <algorithm>
#include <array>
#define ONE 1
#define TWO 2
static_assert(std::ranges::is_sorted({ ONE, TWO }));  // (A)
static_assert(std::ranges::is_sorted(std::array { ONE, TWO }));  // (B)
int main() {}

The underlying temporary array that is allocated for the initializer_list should live until the call to is_sorted() in line (A) has returned.

According to the error message, std::initializer_list cannot be casted to a std::ranges::forward_range: algorithm(10432): 'bool std::ranges::_Is_sorted_fn::operator ()(_Rng &&,_Pr,_Pj) const': could not deduce template argument for '_Rng'.

Is this the same reason as this one?

like image 753
Frank Heimes Avatar asked Oct 21 '25 03:10

Frank Heimes


1 Answers

The problem with your code std::ranges::is_sorted({ ONE, TWO }), is that it cannot deduce the type of { ONE, TWO } within a template parameter.

To actually do this, you must either manually create a initializer_list first:

std::ranges::is_sorted(std::initializer_list{ ONE, TWO })

Or the function itself must not deduce the type of this parameter.


Sidenote, this is one place where the behavior of auto differ from template deduction.

auto is specifically given the ability to deduce il within this syntax:

auto il = {a, b, c};

No other usually equivalent syntaxes can deduce this as initializer_list, including auto il{a, b, c}, template_func({a, b, c}), and etc..

like image 139
Ranoiaetep Avatar answered Oct 23 '25 20:10

Ranoiaetep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!