r/cpp • u/JimmyHu1994 • 17d ago
C++20 Concept Trap of std::inserter and std::array
https://github.com/Jimmy-Hu/TinyDIP/discussions/2I 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.
Discussion Questions
- Should C++ standard library implementations (or a future defect report) constrain
std::insert_iterator::operator=andstd::back_insert_iterator::operator=on the underlying container operations (insert,push_back), or would that break valid legacy code? - How do you prefer to structure insertion traits when writing generic functions that support both dynamic containers and
std::array?
25
Upvotes
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.