Title
Requirements for some algorithms' Size template parameters are unclear
Status
new
Section
[alg.foreach][alg.search] [alg.copy][alg.fill] [alg.generate]
Submitter
Jiang An

Created on 2022-10-05.00:00:00 last changed 26 months ago

Messages

Date: 2022-10-15.00:00:00

[ 2022-10-12; Reflector poll ]

Set priority to 3 after reflector poll.

Date: 2022-10-05.00:00:00

Algorithms std::for_each_n, std::search_n, std::copy_n, std::fill_n, and std::generate_n have similar requirements for the Size template parameter in Mandates, requiring Size to be convertible to an integral type.

However, it is currently underspecified to which integral type Size is converted before further operations. There is implementation divergence:

  • libstdc++ and libc++ use an overload set to determine the target type, and

  • MSVC STL simply chooses std::ptrdiff_t when Size is not an integral type.

It is also notable that when the conversion from the source type to integral types is sufficiently ambiguous, none of these implementations accepts such a source type.

For example, currently the following program is rejected by all mainstream implementations.

#include <algorithm>
#include <cstdio>

struct BadFrom {
  operator short() const { return 1; }
  operator unsigned short() const { return 1; }
};

int main()
{
  int arr[42]{};
  std::for_each_n(arr, BadFrom{}, [&arr](int i)
  {
    std::printf("%d\n", i);
  });
}

I think libc++'s strategy make the most sense. But is it really intended to support using a floating-point type or a class type as Size?

Daniel:

The conversion from class type was indeed intended, see the original wording for LWG 3213, which was transferred to P1718R2.

See also LWG 3439 for a similar underspecified situation for template parameter Distance and for the underspecified Size template parameter in various uninitialized_*_n and destroy_n algorithms in [special.mem.concepts].

ranges::destroy_n has the luxury to simply require iter_difference_t<I>.

History
Date User Action Args
2022-10-12 14:38:10adminsetmessages: + msg12859
2022-10-05 00:00:00admincreate