Some STL implementations actually use object slicing to implement algorithms:
E.g., using iterator_tags
you can easily make std::advance
use the most efficient algorithm:
namespace std {
template <class I>
void advance_impl(I& it, int n, input_iterator_tag) {
for (; n > 0; --n)
++it;
}
// Forward Iterators use the same implementation as Input Iterators...
// TODO:
// Add bidirectional_iterator_tag implementation...
template <class I>
void advance_impl(I& it, int n, random_access_iterator_tag) {
it += n;
}
template <class I>
void advance(I& it, int n) {
advance_impl(it, n, typename iterator_traits<I>::iterator_category());
}
} // std
Using your own little class hierarchy you can disambiguate otherwise ambiguous function overloads. E.g. to convert an object to a std::string
you might want to use the objects member function to_string()
if it exists or otherwise use operator<<
.
struct R2 {}; // rank 2
struct R1 : R2 {}; // rank 1
// C++11.
// Use some type traits and enable_if in C++03.
template <class T>
auto ToString(R1, T const& t) -> decltype(t.to_string()) {
return t.to_string();
}
template <class T>
std::string ToString(R2, T const& t) {
std::ostringstream s;
s << t;
return s.str();
}
template <class T>
std::string ToString(T const& t) {
return ToString(R1(), t);
}