Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting std::sort to random access iterators

I was just wondering, since you can only pass random access iterators to std::sort anyway, why not enforce that restriction by defining it only for random access iterators in the first place?

#include <iterator>
#include <type_traits>

template <typename ForwardIterator>
typename std::enable_if<
    std::is_same<
        typename std::iterator_traits<ForwardIterator>::iterator_category,
        std::random_access_iterator_tag>::value,
    void>
::type sort(ForwardIterator begin, ForwardIterator end)
{
    // ...
}

I find a single line error message a lot easier to read than pages and pages of error messages resulting from type errors far down in the implementation.

You could do the same with other algorithms. The standard C++ core language has always been expressive enough for that task, right? So, any particular reason why this was not done?

like image 671
fredoverflow Avatar asked Jan 22 '11 16:01

fredoverflow


2 Answers

The core language has always been expressive enough to handle such checks, but when the first standard was being prepared (around 1996/1997), the tricks that you can play with SFINAE (what enable_if is based upon) were not yet known and the support for advanced template wizardry was limited in the compilers.

So, the reason why the standard did not mandate it was because the needed techniques were not invented yet.
The reason why compiler/library writers did not add it after the fact is probably just plain economics: not enough people asked for the feature, and when people did start asking for better diagnostics, hope was on the concepts proposal to take care of it. Unfortunately, this proved to be a bit too hard to get finalised in time.

like image 140
Bart van Ingen Schenau Avatar answered Nov 19 '22 02:11

Bart van Ingen Schenau


My guess is that SFINAE was invented (or discovered) after the standard library implementations had reached a certain maturity. After that, changes to the core library had to be very justified in order to prevent the introduction of regressions and I guess that mere cosmetics are somewhat hard to justify.

That said, the GCC for example already does have a lot of diagnostics for template-related error messages, e.g. macros that perform a kind of concept checking. For example, the GCC-libstdc++ has the following:

// concept requirements
__glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
   _RandomAccessIterator>)
__glibcxx_function_requires(_LessThanComparableConcept<_ValueType>)
__glibcxx_requires_valid_range(__first, __last);
like image 3
Konrad Rudolph Avatar answered Nov 19 '22 02:11

Konrad Rudolph