c++ - 泛型的函数对象。

查看:116
本文介绍了c++ - 泛型的函数对象。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

刚才在看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也没有找到答案。
请大家帮忙解答一下。谢谢谢谢。

这个问题已被关闭,原因:问题已解决 - 问题已解决,且对他人无借鉴意义

解决方案

__copy_dispatch<InputIterator,OutputIterator>()

这是调用class

__copy_dispatch<InputIterator,OutputIterator>

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

(fist,last,result)

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

这篇关于c++ - 泛型的函数对象。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆