I’m using a typedef to define the type of a container in my program so that I can easily switch between using normal STL containers and STXXL containers, along the lines of:
typedef stxxl:vector<Data> MyContainer;
or
typedef std:vector<Data> MyContainer;
One difficulty is that STXXL provides a special version of std::for_each, stxxl::for_each that is optimised for use with STXXL containers. I’d prefer to use this function when MyContainer is typedeffed as a stxxl::vector.
One solution would be to define my own for_each function that calls the right for_each function and use that whenever I want to call for_each.
Another solution that I’m currently investigating is to overload/specialize std::foreach so that it calls stxxl::for_each whenever it is called with a stxxl::vector<Data>::(const_)iterator as first and second argument.
I cannot get the second idea to work though. I’ve tried the following:
namespace std
{
template <class UnaryFunction>
UnaryFunction for_each(stxxl:vector<Data>::const_iterator first,
stxxl:vector<Data>::const_iterator last, UnaryFunction f)
{
stxxl::for_each(first, last, f, 4);
}
}
Along with a similar function for non-const iterators. They don’t get called though.
What would be the preferred solution to this problem? How can I get my version of std::for_each for stxxl::vector iterators to get called?
Update: I got the second idea to work now, as posted. The problem was that I was including the wrong file (ouch…). The first question remains though: What is the preferred solution to this problem? Is it okay to overload std::for_each, as the std namespace is not intended for mere mortals?
You can specialize templates in std (17.4.3.1), but you can’t add overloads. Your definition is an overload, not a specialization of the standard for_each template, and in any case functions can’t be partially specialized. So it’s undefined to put any definition in namespace std that might do what you want.
ADL is supposed to make this work smoothly without any need for that, though. I assume the stxxl iterators are in the stxxl namespace, so
for_each(first, last, f, 4);should callstxxl::for_each. If you wantstd::for_each, you fully qualify the name when you call it.