Home  >  Q&A  >  body text

c++ - Generic function object.

I just saw this piece of code when I was looking at the stl source code analysis copy function

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));
    }    
};

This __copy_dispatch is a struct with an overloaded () operator. When called in copy, it directly

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

Directly The () operator is called using this struct, but is not called with a stuct object .

Is this okay? I quickly looked through c++primer and couldn't find the answer.
Please help me answer this question. thanks, thanks.

淡淡烟草味淡淡烟草味2685 days ago824

reply all(3)I'll reply

  • 習慣沉默

    習慣沉默2017-05-16 13:24:50

    __copy_dispatch<InputIterator,OutputIterator>()

    This is calling class

    __copy_dispatch<InputIterator,OutputIterator>
    The default constructor of

    , its function is to generate a temporary object. Next

    (fist,last,result)
    The function of

    is to call operator() on this temporary object with first, last, and result as actual parameters.

    reply
    0
  • 怪我咯

    怪我咯2017-05-16 13:24:50

    Using this struct, the () operator is called. This is the meaning of functor. Its function here is to create an unnamed object

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-16 13:24:50

    In fact, lambda also created a class that overloads operator() to achieve the effect of functor.

    reply
    0
  • Cancelreply