I’m using VS2008 (so I have TR1, but no C++11), and I don’t use boost.
The description that follows is a simplified version of my real problem.
I have the following class hierarchy: an interface, an abstract class that implements it and several classes derived from that abstract class:
struct IMyInterface
{
virtual void MinMax(int& Min, int& Max)const = 0;
};
class Base : public IMyInterface // Abstract
{
// ...
};
class A: public Base
{
public:
virtual void MinMax(int& Min, int& Max)const { // Some stuff for A}
// ...
};
class B: public Base
{
public:
virtual void MinMax(int& Min, int& Max)const { // Some stuff for B}
// ...
};
Then I have a vector of shared_ptr to the Base class:
// Somewhere in my code
typedef shared_ptr<Base> Base_sp;
vector<Base_sp> v;
And I have some code that does this:
int Vmin = INT_MAX;
int Vmax = INT_MIN;
for(vector<Base_sp>::const_iterator it = v_sp.begin(); it != v_sp.end(); ++it)
{
int v1, v2;
(*it)->MinMax(v1, v2);
Vmin = std::min(v1, Vmin);
Vmax = std::max(v2, Vmax);
}
I use similar code in more than one place so I’ve taken it out to a function I run through accumulate:
pair<int, int> MinMaxFinder(pair<int, int> vals, Base_sp elem)
{
int Vmin = vals.first;
int Vmax = vals.second;
if (elem)
{
int v1, v2;
elem->MinMax(v1, v2);
Vmin = std::min(v1, Vmin);
Vmax = std::max(v2, Vmax);
}
return make_pair(Vmin, Vmax);
}
pair<int, int> tmp = accumulate(v_sp.begin(), v_sp.end(),
make_pair(INT_MAX, INT_MIN), &MinMaxFinder);
int Vmin = tmp.first;
int Vmax = tmp.second;
This works fine, but, in the other places where I use the code I want to replace, I do not necessarily use Base_sp-derived classes, but other IMyInterface-derived classes. So I would like to declare MinMaxFinder like this:
pair<int, int> MinMaxFinder(pair<int, int> vals, IMyInterface* elem)
But that, of course, doesn’t compile.
So, is there a way, through an adapter or something, to do what I want? If not, any ideas on how to tackle this?
You could parametrise the function over the type of pointer used:
For convenience, this could be further wrapped in a function parametrised by the container type: