Passing Function name as arguments to a function

Balanivash picture Balanivash · Jun 15, 2011 · Viewed 11.6k times · Source

Is it possible to pass the name of a function(say A) as an argument to another function (say B), and then call function A from function B. That is the function name will be stored in a variable in B, and using it call the function whose name is in the variable. For Example in C++ sort function the first and second arguments are iterators, but the third argument is the name of a function.

Answer

fredoverflow picture fredoverflow · Jun 15, 2011

You can introduce a template parameter (here Pred) for "anything that is callable with two parameters":

template <typename Iter, typename Pred>
void mysort(Iter begin, Iter end, Pred predicate)
{
    --end;
    // ...
        if (predicate(*begin, *end))
        {
            // ...
        }
    // ...
}

Then you can pass either good old C function pointers or C++ function objects:

bool function(int x, int y)
{
    return x < y;
}

struct function_object
{
    bool operator()(int x, int y)
    {
        return x < y;
    }
};

int main()
{
    int numbers[] = {543, 6542654, 432514, 54, 45, 243};
    mysort(numbers + 0, numbers + 6, &function);
    mysort(numbers + 0, numbers + 6, function_object());
}

As you can see, a function object is an object of a class that overloads operator() appropriately.