如何定义自己的函数对象,它使用于任何的绑定器
要定义自己的绑定器要满足一定的条件:必须提供参数和返回值的类型。
STL
为我们提供了两个结构体:
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
template <class Argl, class Arg2, class Result>
struct binary_function {
typedef Argl first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
一个例子:
template <class T1, class T2>
struct fopow : public std::binary_function<T1, T2, T1>
{
T1 operator() (T1 base, T2 exp) const {
return std::pow(base,exp);
}
};
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
transform (coll.begin(), coll.end(), //source
ostream_iterator<int>(cout," "), //destination
bind1st(fopow<float ,int>() ,3)); //operation
cout << endl;
output:
3 9 27 81 243 729 2187 6561 19683.
在我们自定以函数对象时也不必非要继承那两个结构体,在自己类指定相关类型也可以。
要定义自己的绑定器要满足一定的条件:必须提供参数和返回值的类型。
STL
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
template <class Argl, class Arg2, class Result>
struct binary_function {
typedef Argl first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
一个例子:
template <class T1, class T2>
struct fopow : public std::binary_function<T1, T2, T1>
{
T1 operator() (T1 base, T2 exp) const {
return std::pow(base,exp);
}
};
for (int i=1; i<=9; ++i) {
coll.push_back(i);
}
transform (coll.begin(), coll.end(), //source
ostream_iterator<int>(cout," "), //destination
bind1st(fopow<float ,int>() ,3)); //operation
cout << endl;
output:
3 9 27 81 243 729 2187 6561 19683.
在我们自定以函数对象时也不必非要继承那两个结构体,在自己类指定相关类型也可以。