将 std::map 中元素的位置作为参数传递给被调用函数

Passing position of element in std::map as argument to called function

说,我有两个功能:

int methodA(int);
int methodB(int);

为了避免重复下面给出的大块代码,我想创建一个单独的函数(比如,funcToAvoidRepeatedCode),它接受函数指针:

{
    //...many lines of code

    std::multimap< size_t, std::pair<char, size_t> >::iterator it;

    //...many lines of code

    methodA(it->first); OR methodB(it->second.second);  // << This is the only difference. 

    //...many lines of code
}

我知道如何使用 std::function 传递函数指针。我希望将上面的代码行更改为这种形式:

void funcToAvoidRepeatedCode(funcPtr, ?????){

    //...many lines of code

    std::multimap< size_t, std::pair<timelineWeakRef, size_t> >::iterator it;

    //...many lines of code

    funcPtr(???????);
                ^~~~~~What kind of parameter I can pass to 
                      funcToAvoidRepeatedCode() to differentiate the                                          
                      position (first or second.second) in map element?

    //...many lines of code
}

我该如何做到这一点?

根据给定的信息,有一个简单的方法可以实现:编写另一组包装函数。

int methodAWrapper(std::multimap< size_t, std::pair<char, size_t> >::iterator it) {
    return methodA(it->first);
}

int methodBWrapper(std::multimap< size_t, std::pair<char, size_t> >::iterator it) {
    return methodB(it->second.second);
}

然后不传递 methodAmethodB 作为函数指针,而是传递 methodAWrappermethodBWrapper.

funcToAvoidRepeatedCode 然后简单地做

void funcToAvoidRepeatedCode(funcPtr) {
    ...
    funcPtr(it);
    ...
}

这样 funcToAvoidRepeatedCode 只包含公共代码,所有差异都提取到辅助方法 A 和 B 中。(如果 methodAmethodB 没有其他用途,您甚至可以将它们内联到 methodAWrappermethodBWrapper,因此函数的数量保持不变。)

我可能遗漏了一些东西,但你显然有某种条件表明你应该使用 methodA 还是 methodB。那么,为什么不将该条件传递给函数并避免完全使用函数指针呢。

void funcToAvoidRepeatedCode(condition) 
{
    if(condition)
    {
        methodA(...);
    }
    else
    {
        methodB(...);
    }
}

如果可以传递某个签名的任意函数(例如 sort() 中的比较器),则需要传递函数指针,但在这种情况下不需要。