Re: How to pass a binary_function functor as an argument?
{ Quoted clc++m banner removed. Note: most newsreaders will remove the
banner (and other signature content) automatically when quoting an
earlier article; AFAIK only Google Groups does not. -mod/aps }
t_littell@yahoo.com wrote:
I want to pass a binary_function<double, double, double> functor
object as an argument into another function. So, I tried the
following which does not work with std::accumulate():
class BinFunctor : public std::binary_function<double, double, double>
{
public:
// I've tried with & without pure virtual method here, no luck.
virtual double operator()(const double& x, const double& y) const =
0;
};
class SumFunctor : public BinFunctor
{
public:
double operator()(const double& x, const double& y) const { return x
+y; }
};
class ProductFunctor : public BinFunctor {...};
//... many other BinFunctor classes defined.
double foo(const vector<double>& vec, double init, BinFunctor& bf)
{
return std::accumulate(vec.begin(), vec.end(), init, bf); //
COMPILE ERROR HERE
// also tried: bf() bf::operator() nothing works
}
int main()
{
SumFunctor sf;
double res = foo(vec, 0, sf);
}
template <typename T1>
class SumFunctor : public std::binary_function<T1, T1, T1>
{
public:
T1 operator()(const T1& x, const T1& y) {
return x+y;
}
};
int main()
{
std::vector<double> vectorum(5,0.2);
double test1 = accumulate(vectorum.begin(), vectorum.end(), 0.1,
SumFunctor<double>());
double test = accumulate(vectorum.begin(), vectorum.end(), 0.1,
std::plus<double>());
};
I gave two options to fix the problem. First one is to use std::plus
and another one is
to use your own SumFunctor.
I think to use std::plus would be a better choice in your case rather
than rewriting SumFunctor as something exactly the same as std::plus.
I would recommend to check standart library first rather than writing
your own similar/same functionality.
Regards
Cumhur Guzel
www.ir.com
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]