https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107092
Bug ID: 107092
Summary: std::for_each_n and its friends incorrectly accept
size parameters that are not convertible to an integer
type
Product: gcc
Version: 12.1.0
Status: UNCONFIRMED
Keywords: accepts-invalid
Severity: normal
Priority: P3
Component: libstdc++
Assignee: unassigned at gcc dot gnu.org
Reporter: de34 at live dot cn
Target Milestone: ---
This program shouldn't compile due to [alg.foreach]/16:
> Mandates: The type Size is convertible to an integral type ([conv.integral],
> [class.conv]).
It's obvious that BadFrom can't be converted to any integral type.
#include <algorithm>
#include <concepts>
struct BadFrom {
template<std::same_as<double> D>
operator D() const
{
return 42.0;
}
};
int main()
{
int arr[42]{};
std::for_each_n(arr, BadFrom{}, [](int){});
}
However, this is accepted by libstdc++, because the conversion is done by
__size_to_integer overloads in stl_algobase.h (added via PR 87982), and
overloads for floating-point types are (probably) incorrectly provided.
Godbolt link: https://godbolt.org/z/EKvx7dY4e
While I believe the current "is convertible to an integral type" requirement is
defective (as ambiguity is not considered at all), I think libstdc++ should
reject using BadFrom as Size.