Re: problem in stl
this is a nice one.
I can use that too!
Thanks,
Bas from Holland
"Michael Doubez" <michael.doubez@free.fr> wrote in message
news:01cf54a1-8635-4f8a-9e98-8388c023ef3f@g19g2000yqe.googlegroups.com...
On 15 f?v, 23:32, "Alf P. Steinbach" <al...@start.no> wrote:
* Pete Becker:
Juha Nieminen wrote:
Alf P. Steinbach wrote:
But that doesn't work for std::list, so std::list
has a sort() member function (presumably it uses merge sorting or some
such that's better suited for linked lists), and overrides std::sort
to
call that member function.
How could <list> overload std::sort() to call std::list::sort() given
that std::sort() is given two iterators, not the original data
container?
It doesn't.
Sorry for the confusion in that article (note the brain-to-keyboard errors
also,
which I had to post follow-up to correct).
I was confusing sort with swap.
Or in other words, the whole article was mostly wrong, rubbish.
It leads to an interesting practical question though, how to write
template< T >
void sort_any_container( T& c );
without doing those overloads.
The usual meta-programming tricks:
// predicate to test the presence of member
typedef char (&no_tag)[1];
typedef char (&yes_tag)[2];
template <typename T, void (T::*)()>
struct ptmf_helper {};
template<typename T>
no_tag has_member_sort_helper(...);
template<typename T>
yes_tag has_member_sort_helper(ptmf_helper<T, &T::sort>* p);
// helper
template< typename T
, bool has_sort
= sizeof(has_member_sort_helper<T>(0))== sizeof(yes_tag)
>
struct type_has_sort{};
// if has sort member
template< class T >
void sort_any_container_helper(T& c , const type_has_sort<T,true>&)
{
c.sort();
}
// otherwise rely on algorithm
template< class T >
void sort_any_container_helper(T& c , const type_has_sort<T,false>&)
{
std::sort(c.begin(), c.end());
}
// main template
template< class T >
void sort_any_container( T& c )
{
sort_any_container_helper(c,type_has_sort<T>());
}
main()
{
using namespace std;
vector<int> vec;
list <int> lis;
sort_any_container(vec);
sort_any_container(lis);
}
--
Michael