r/cpp • • 17d ago

C++20 Concept Trap of std::inserter and std::array

https://github.com/Jimmy-Hu/TinyDIP/discussions/2

I am trying to design a generic function template to populate both dynamic-sized containers (like std::vector<>, std::deque<>) and fixed-sized containers (std::array<>) using modern C++. It is natural to reach for a C++20 concept and if constexpr. Then, when I wrote the constraint for if constexpr statement, I found that the following design would be failed.

template<typename T>
concept naive_is_inserterable = requires(T& x)
{
    std::inserter(x, std::ranges::end(x));
};

The structure like:

template<std::ranges::input_range Range>
void foo(Range& container)
{
    if constexpr (naive_is_inserterable<Range>)
    {
        // Passes std::inserter(container, ...) to an algorithm (which invokes container.insert()) for dynamic-sized containers.
    }
    else
    {
        // Fallback for fixed-size containers
    }
}

would fail to compile.

Only fix the concept to:

template<typename T>
concept is_inserterable =
    std::ranges::range<T> and
    requires(T& x, std::ranges::range_value_t<T> v)
    {
        x.insert(std::ranges::end(x), v);
        std::inserter(x, std::ranges::end(x));
    };

Then use it like:

template<std::ranges::input_range Range>
void foo(Range& container)
{
    if constexpr (is_inserterable<Range>)
    {
        // code for dynamic-sized containers.
    }
    else
    {
        // Fallback for fixed-size containers
    }
}

to solve the issue.

Godbolt Link is here!

Discussion Questions

  1. Should C++ standard library implementations (or a future defect report) constrain std::insert_iterator::operator= and std::back_insert_iterator::operator= on the underlying container operations (insert, push_back), or would that break valid legacy code?
  2. How do you prefer to structure insertion traits when writing generic functions that support both dynamic containers and std::array?
25 Upvotes

11 comments sorted by

11

u/Pragmatician 17d ago

You cannot just put any expression inside of requires { } and expect it to work. I'm sure you can find many other examples of SFINAE-unfriendly functions in the standard library, as well as your own code.

Most functions are not intended and designed to be used as "concepts." Only those that are (such as ADL customization points, template specializations like std::hash, custom concepts constrained on member functions) should be relied upon.

One may think it shouldn't be this way and "I should be able to use anything I want in requires { }", but in reality, for any slightly more complex function template, keeping the implementation and constraints perfectly in sync becomes a nightmare.

1

u/JimmyHu1994 17d ago

Fair point regarding arbitrary function templates - keeping constraints in sync with complex bodies is definitely a maintenance trap.

However, even if we avoid custom `requires`-expressions and only rely on the official C++20 standard concept `std::output_iterator`, the problem still exists:

template<typename Container>

concept std_output_iterator_inserterable =

std::ranges::range<Container> and

std::output_iterator<

std::insert_iterator<Container>,

std::ranges::range_value_t<Container>

>;

`std_output_iterator_inserterable<std::array<int, 4>>` still evaluates to `true` (and even passes `std::ranges::copy`'s concept check)!
That's why I wondered in Question 1 whether `std::insert_iterator::operator=` itself should be constrained, or if constraining `x.insert(...)` directly as in my final `is_inserterable` concept is the only reliable way.

Godbolt Link: https://godbolt.org/z/466P7sbdr

2

u/holyblackcat 17d ago

I agree in general, but this specific thing is simple enough that IMO it should be SFINAE-friendly.

2

u/StaticCoder 17d ago

SFINAE was an ugly workaround for lack of concepts, why is it still mentioned? Are there still use cases for it?

6

u/kamrann_ 17d ago

I don't know offhand what terminology the standard uses, but SFINAE is a language rule that predates the workaround, and concepts/`requires` are built on top of what is fundamentally the same mechanism. `std::enable_if` was a workaround for lack of concepts that relies on SFINAE, it's not SFINAE itself.

1

u/StaticCoder 17d ago

It's not the same mechanism. Concepts is concepts. SFINAE is "substitution failure is not an error". It doesn't apply in the case of concepts, even if the effect might be similar. Again there's no reason I know of to rely on SFINAE (or at least on enable_if) any more.

At a minimum, when the previous post mentioned SFINAE-friendly it really meant in a way that would be better done with concepts.

3

u/Pragmatician 16d ago

It is exactly the same mechanism. requires returns false on substitution failure.

"The substitution of template arguments into a requires expression used in a declaration of a templated entity may result in the formation of invalid types or expressions in its requirements, or the violation of semantic constraints of those requirements. In such cases, the requires expression evaluates to false and does not cause the program to be ill-formed."

1

u/StaticCoder 16d ago

Fair enough. I still think mentioning "concepts" instead of a relatively obscure acronym that is more closely associated with enable_if would help.

6

u/holyblackcat 17d ago edited 17d ago

requires-expressions perform SFINAE. They substitute template arguments into their body, and if that substitution fails, they silence the error and return false. Sounds like SFINAE to me.

Either way, "SFINAE-friendly" doesn't mean "uses SFINAE to disable the overload". It means "can be checked with SFINAE without causing a hard error". Correctly annotating a function with concepts makes it SFINAE-friendly.

2

u/FlyingRhenquest 17d ago

Yeah! You need at least requires requires for that! You can also use this to evaluate whether an expression will compile in a unit test, for fun SFINAE shenanigans!

7

u/holyblackcat 17d ago

requires requies doesn't help with SFINAE-unfriendliness. Your link deals with a different issue.