combining 3 functors into 1
I have 3 functors and was wondering if these can be combined into 1, perhaps as a template. is it possible? if so, how would I do it. thx!
struct less_than
{
bo开发者_JS百科ol operator()(double prev,double curr) const
{
return prev<curr;
}
};
struct great_than
{
bool operator()(double prev,double curr) const
{
return prev>curr;
}
};
struct equal_to
{
bool operator()(double prev, double curr) const
{
return prev==curr;
}
};
If you mean, specialized by the operator, then the answer is, no, not at the language level.
Luckily, the STL already provides functors for this (std::equal_to
, etc.). You can either use these directly, or use them as arguments to your own function classes.
As these are all existent in the standard library, you can just do
template<class F>
struct compare
{
compare(F _f)
: f(_f) {};
bool operator()(double prev, double curr) const
{
return f(prev, curr);
}
F f;
};
And use e.g. compare< std::less<double> >
. But this would be quite useless, as you can just use the standard library functors directly.
You can do something like this:
class Functors
{
private:
bool f1(double, double)
{
}
bool f2(double, double)
{
}
bool f3(double, double)
{
}
public:
bool test(int op, double a, double b)
{
//better use function selector, this is only simple example
if (op == 1)
return f1(a, b);
if (op == 2)
return f2(a, b);
if (op == 3)
return f3(a, b);
}
};
use it:
vector<double> v;
int op = select_op();
//sort vector
std::sort(v.begin(), v.end(), boost::bind(&Functors::test, Functors(), op, _1, _2));
精彩评论