30-其他方式
18.5.3 其他方式
下面介绍使用function可完成的其他两项任务。首先,在程序清单18.8中,不用声明6个function<double (double)>对象,而只使用一个临时function<double (double)>对象,将其用作函数use_f()的参数:
typedef function<double(double)> fdd; // simplify the type declaration
cout << use_f(y, fdd(dub)) << endl; // create and initialize object to dub
cout << use_f(y, fdd(square)) << endl;
...
其次,程序清单18.8让use_f()的第二个实参与形参f匹配,但另一种方法是让形参f的类型与原始实参匹配。为此,可在模板use_f()的定义中,将第二个参数声明为function包装器对象,如下所示:
#include <functional>
template <typename T>
T use_f(T v, std::function<T(T)> f) // f call signature is T(T)
{
static int count = 0;
count++;
std::cout << " use_f count = " << count
<< ", &count = " << &count << std::endl;
return f(v);
}
这样函数调用将如下:
cout << " " << use_f<double>(y, dub) << endl;
...
cout << " " << use_f<double>(y, Fp(5.0)) << endl;
...
cout << " " << use_f<double>(y, [](double u) {return u*u;}) << endl;
参数dub、Fp(5.0)等本身的类型并不是function<double(double)>,因此在use_f后面使用了