Search code examples
c++functor

Calling a functor "pointed to" by an iterator inside a template function


The template function apply_all below takes an iterator range (itBegin -> itEnd) for a sequence of binary function objects stored in a vector. As I iterate, I want each functor to be called with the two given arguments a and b. The result is to be written to the Output Iterator (outIt), but I have no idea how to call a functor using the iterator variable:

template <typename InIt, typename OutIt, typename A, typename B>
void apply_all(InIt itBegin, InIt itEnd, OutIt outIt, const A& a, const B& b)
{
    for(auto it = itBegin; it != itEnd; it++)
    {
        *outIt = ... // how do I call the functor pointed to by *it?
        outIt++;
    }
}

Solution

  • In C++17, simply using std::invoke

    *outIt = std::invoke(*it, a, b);
    

    or plain (if not a pointer to member function)

    *outIt = (*it)( a, b);