当前位置:嗨网首页>书籍在线阅读

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后面使用了来指出所需的具体化。这样,T被设置为double,而std::function<T(T)>变成了std::function<double(double)>。