The following is my attempt to implement a insert_sorted() C++ function that accepts any sorted STL container and item and inserts it at the right position in the container:
template<template<typename, typename, typename> typename C, typename T1, typename Comp, typename A, typename T2>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, Comp, A>::iterator
insert_sorted (C<T1, Comp, A> & c, T2 && item)
{
return c.insert (c.end(), std::forward<T2> (item));
}
template<template<typename, typename> typename C, typename T1, typename A, typename T2, typename Comp = std::less<T1>>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, A>::iterator
insert_sorted (C<T1, A> & c, T2 && item, Comp comp = Comp{})
{
return c.insert (std::upper_bound (std::begin (c), std::end (c), static_cast<T1>(item), comp), std::forward<T2> (item));
}
These two compile and work fine; the first overload works for set-like containers, while the second for vector-like containers.
I was wondering if you see any drawbacks to this solution and if there is a more generic way to approach the problem, that is, is it possible to write a single insert_sorted() function that does the same as the above two?
EDIT: Thanks to the comments, I was able to replace the two template functions above with the following:
template<typename C, typename T, typename Comp = std::less<T>,
typename = std::enable_if<std::is_convertible_v<std::remove_reference_t<T>, typename C::value_type>>>
inline auto insert_sorted (C & c, T && item, Comp comp = Comp{})
{
return c.insert (std::upper_bound (std::begin (c), std::end (c), item, comp), std::forward<T> (item));
}
Thank you all for your help!