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

70 Views Asked by At

Say, I have two functions:

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

To avoid repetition of the given below big chunk of code I want create a separate function (say, funcToAvoidRepeatedCode), which takes function pointer:

{
    //...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
}

I know how to pass the function pointer using std::function. I am looking to change the above lines of code into this form:

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
}

How do I accomplish this?

2

There are 2 best solutions below

0
On BEST ANSWER

I may be missing something, but you clearly have some kind of condition there that indicates whether you should use methodA or methodB. So why don't you pass that condition into the function instead and avoid using function pointers altogether.

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

Passing a function pointer would be required if an arbitrary function of some signature can be passed (e.g. the comparator in sort()), but in this case it is not needed.

3
On

Based on the information given, there's a simple way to achieve this: Write another set of wrapper functions.

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

Then instead of passing methodA or methodB as the function pointer, you pass methodAWrapper or methodBWrapper.

funcToAvoidRepeatedCode then simply does

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

This way funcToAvoidRepeatedCode contains only the common code and all differences are extracted into helper methods A and B. (If there are no other uses of methodA and methodB, you can even inline them into methodAWrapper and methodBWrapper, so the number of functions stays the same.)