
operator().
#include < iostream.h >
template < class T >
struct square {
T operator()(T n) {return n*n;}
};
template < class T, class funcObj >
void printEval(T val,funcObj f) {
cout << f(val) << endl;
};
main() {
printEval(1.4, square < float > ());
printEval(1.4, square < int > ());
return 0;
}
output:
1.96 1
template < class T >
struct sum_square {
T & counter;
sum_square(int &c): counter(c) {counter=0;}
T operator()(T n) {
T temp = n*n;
counter += temp;
return temp;
}
};
...
int test[20]
...
ostream_iterator < int > output (cout," ");
...
int sum;
transform(test,test+20,output,sum_square < int > (sum));
cout << "Sum of squares = " << sum;
Function Object | Type | Return |
|---|---|---|
| Arithmatic function objects | ||
| plus | binary | arg1 + arg2 |
| minus | binary | arg1 - arg2 |
| times | binary | arg1 * arg2 |
| divides | binary | arg1 / arg2 |
| modulus | binary | arg1 % arg2 |
| negate | unary | -arg1 |
| ident | unary | arg1 |
| Comparison function objects | ||
| equal_to | binary | arg1 == arg2 |
| not_equal_to | binary | arg1 != arg2 |
| greater | binary | arg1 > arg2 |
| less | binary | arg1 < arg2 |
| greater_equal | binary | arg1 >= arg2 |
| less_equal | binary | arg1 <= arg2 |
| Logical function objects | ||
| logical_and | binary | arg1 && arg2 |
| logical_or | binary | arg1 || arg2 |
| logical_not | unary | !arg1 |
template < class Operation1, class Operation2, class Operation3 >
class binary_compose : public unary_function< Operation2::argument_type,
Operation1::result_type > {
protected:
Operation1 op1;
Operation2 op2;
Operation3 op3;
public:
binary_compose(const Operation1& x, const Operation2& y,
const Operation3& z) : op1(x), op2(y), op3(z) { }
result_type operator()(const argument_type& x) const {
return op1(op2(x), op3(x));
}
};
compose2(const Operation1& op1, const Operation2& op2, const Operation3& op3) {
return binary_compose(op1, op2, op3);
}
Example use:
//outi == ai2 + 2ai
transform(a.begin(),a.end(),out,
compose2(add< int >(),
square< int >(),
bind1st(mult< int >(),2)));
Function adaptor | Argument types | Result object type | Result class |
|---|---|---|---|
| not1 | bool fn(arg) | bool fn(arg) | unary_negate< > |
| not2 | bool fn(arg1,arg2) | bool fn(arg1,arg2) | binary_negate< > |
| bind1st | T fn(arg1,arg2),x | T fn(arg) | binder1st< > |
| bind2nd | T fn(arg1,arg2),x | T fn(arg) | binder2nd< > |
| ptr_fun | T (*fn)(arg) | T fn(arg) | pointer_to_unary_function< > |
| ptr_fun | T (*fn)(arg1,arg2) | T fn(arg1,arg2) | pointer_to_binary_function< > |
| compose1 | T fn(arg), T fn2(arg) | T fn(arg) | unary_compose< > |
| compose2 | T fn(arg1,arg2), T fn2(arg),T fn3(arg) | T fn(arg) | binary_compose< > |