H
hn.ft.pris
I've got following code test C++'s functor. For the sake of
easy-reading, I omit some declearations.
#include <algorithm>
#include <functional>
using namespace std;
template <typename T> class Sum{
public:
Sum(T i=0):sum(i){};
inline void operator () (T x){
sum += x;
}
inline T output() const{
return sum;
}
private:
T sum;
};
int main( void ){
vector<int> vec(10, 1);
Sum<int> sum;
sum = for_each(vec.begin(), vec.end(), Sum<int>()); .......(1)
sum = for_each(vec.begin(), vec.end(), sum); .........(2)
sum = for_each(vec.begin(), vec.end(), sum.operator()(int) ); ...(3)
cout << sum.output() << endl;
return 1;
}
It's easy to understand that (2) works, because sum.operator()(int) is
called implicitly. (1) also works, it confuses me. Does Sum<int>()
create an implicit class Sum object? On the other hand, Sum<int>
doesn't work.
(3) fails, does it means the third argument of "for_each" couldn't be a
function pointer? What will the code be if I want to pass a function
pointer here? Thanks for help!
easy-reading, I omit some declearations.
#include <algorithm>
#include <functional>
using namespace std;
template <typename T> class Sum{
public:
Sum(T i=0):sum(i){};
inline void operator () (T x){
sum += x;
}
inline T output() const{
return sum;
}
private:
T sum;
};
int main( void ){
vector<int> vec(10, 1);
Sum<int> sum;
sum = for_each(vec.begin(), vec.end(), Sum<int>()); .......(1)
sum = for_each(vec.begin(), vec.end(), sum); .........(2)
sum = for_each(vec.begin(), vec.end(), sum.operator()(int) ); ...(3)
cout << sum.output() << endl;
return 1;
}
It's easy to understand that (2) works, because sum.operator()(int) is
called implicitly. (1) also works, it confuses me. Does Sum<int>()
create an implicit class Sum object? On the other hand, Sum<int>
doesn't work.
(3) fails, does it means the third argument of "for_each" couldn't be a
function pointer? What will the code be if I want to pass a function
pointer here? Thanks for help!