c++ - 泛型的函数对象。
淡淡烟草味
淡淡烟草味 2017-05-16 13:22:50
0
3
829

刚才在看stl源码剖析copy函数时看到了这么一段代码

template<class InputIterator,class OutputIterator>
inline OutputIterator copy(InputIterator first,InputIterator last,OutputIterator result)
{
    return __copy_dispatch<InputIterator,OutputIterator>()(fist,last,result);//这是个函数
}

//这是完全泛化的的版本。
template <class InputIterator,class OutputIterator>
struct __copy_dispatch
{
    OutputIterator operator()(InputIterator first,InputIterator last,OutputIterator result)
    {
        return __copy(first,last,result,iterator_category(first));
    }    
};

这个__copy_dispatch是一个重载了()运算符的struct,在copy中调用的时候时候,他直接

__copy_dispatch<InputIterator,OutputIterator>()(fist,last,result);

直接用这个struct就调用了()运算符,而不是用一个stuct对象来调用。

请问这样可以?我快速翻了c++primer也没有找到答案。
请大家帮忙解答一下。谢谢谢谢。

淡淡烟草味
淡淡烟草味

全部回复(3)
習慣沉默
__copy_dispatch<InputIterator,OutputIterator>()

这是调用class

__copy_dispatch<InputIterator,OutputIterator>

的默认构造函数,它的作用是生成一个临时对象。接下来

(fist,last,result)

的作用则是以first, last, result为实参,在这个临时对象上调用operator()。

刘奇

用这个struct就调用了()运算符,这是仿函数的意思,它在这里的作用就是创建一个不具名的对象

習慣沉默

其实lambda也是创建了一个重载了operator()的类来实现仿函数的效果的.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!