How can std::ranges work with initializer_list?

334 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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..