Re: template function object for accumulate
er wrote:
pls i need help with
a) understanding the error at the bottom of the code
b) making another function object, (almost) identical to
Accumulate_op, say Accumulate_const_op whose operator is defined as R
operator()(R sum_so_far,const C& obj)const
what would be the best way? i'm hoping i can create a more general
Accumulate_op with an extra par to specify if C& should be const or
not.
See below.
//here is the code:
template<typename C,typename R,R (C::*F)()> class Accumulate_op:
public std::binary_function<R,C,R>{//,typename R (C::*F)()
public:
Accumulate_op(){};
R operator()(R sum_so_far,C& obj)const;
};
template<typename C,typename R,R (C::*F)()> R
Accumulate_op<C,R,F>::operator()(R sum_so_far,C& obj)const{
return sum_so_far+(obj.*F)();
};
class Test{
public:
Test(){};
long double get(){return 0.9;};
};
int main(){
Test t;
std::vector<Test> vec(3);
vec.push_back(t);
vec.push_back(t);
vec.push_back(t);
So, your total number of vector elements is 6 here...
std::cout<<
std::accumulate(
vec.begin,
vec.end(),
0.0,
Accumulate_op<Test,long double,&Test::get>()
)<<std::endl;//error shows here
return 0;
}
//end of code
error: conversion from '<unresolved overloaded function type>' to
non-scalar type '__gnu_cxx::__normal_iterator<Test*,
std::vector<Test,
std::allocator<Test> > >' requested
OK, you solved this one. Here is what I propose:
===================================================================
class Test {
public:
long double get() { return 0.9; }
};
class TestConst {
public:
long double get() const { return 0.9; }
};
#include <numeric>
#include <vector>
#include <iostream>
template<typename C, typename R, typename Ff>
class Accumulate_op_T {
Ff F;
public:
Accumulate_op_T(Ff f) : F(f) {}
R operator()(R sum_so_far, C& obj) const
{
return sum_so_far + (obj.*F)();
}
};
template<typename C, typename R, typename Ff>
Accumulate_op_T<C,R,Ff> Accumulate_op(Ff f) {
return Accumulate_op_T<C,R,Ff>(f);
}
int main(){
Test t;
std::vector<Test> vec(3, t);
TestConst tc;
std::vector<TestConst> vecc(4, tc);
std::cout
<< std::accumulate(
vec.begin(),
vec.end(),
0.0,
Accumulate_op<Test, long double>(&Test::get))
<< std::endl;
std::cout
<< std::accumulate(
vecc.begin(),
vecc.end(),
0.0,
Accumulate_op<TestConst, long double>(&TestConst::get))
<< std::endl;
return 0;
}
===================================================================
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask