Tyler Gaona
Tyler Gaona

Reputation: 489

What is the difference between using function pointers or an object when passing a function to a template?

Suppose I wanted to implement std::find_if from <algorithm>. Here is one possible way I tried that works.

template <class In, class F>
In find_if(In b, In e, F f)
{
    while (b != e)
    {
        if (f(*b))
            return b;
        b++;
    }
    return e;
}

Here it seems that the user needs to know to pass an argument that returns a bool value. Part of my question regards if there is any way to restrict what is passed to F f using this technique.

Another way to implement this would involve the use of function pointers:

template <bool (*F)(int), class In>
In find_if(In b, In e)
{
    while (b != e)
    {
        if (F(*b))
            return b;
        b++;
    }
    return e;
}

Are there any differences between these two methods (other than the way they must be called; i.e the first way is called with find_if(arg1,arg2,f) and the second way is called withfind_if<f>(arg1,arg2).

If there are differences, could you please delineate and explain them to me?

Upvotes: 2

Views: 126

Answers (1)

Jarod42
Jarod42

Reputation: 217245

Passing a function pointer is more restrictive than passing a type where we apply (*b) on it.

In the case of the class, you may pass

  • functor class (which may have state) as:

    struct HasName {
        explicit HasName(const std::string& name) : name(name) {}
    
        template <typename T>
        bool operator () (const T& t) const { return t.get_name() == name; }
    
        std::string name;
    };
    
  • or any function pointer where f(*b) is correct (so f can take float whereas *b is an int, for example).

  • or lambda (C++11).

Upvotes: 2

Related Questions