首页 > 解决方案 > 调用模板函数内的迭代器“指向”的函子

问题描述

下面的模板函数为存储在向量中的一系列二进制函数对象apply_all采用迭代器范围 ( )。当我迭代时,我希望使用两个给定的参数和. 结果将被写入( ),但我不知道如何使用迭代器变量调用仿函数:itBegin -> itEndabOutput IteratoroutIt

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

标签: c++functor

解决方案


在 C++17 中,只需使用std::invoke

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

或普通(如果不是指向成员函数的指针)

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

推荐阅读