将函数传递给模板时使用函数指针或对象有什么区别

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

本文关键字:函数 指针 对象 什么 区别      更新时间:2023-10-16

假设我想从<algorithm>实现std::find_if。这是我尝试的一种可能的方法。

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

在这里,用户似乎需要知道传递一个返回bool值的参数。我的部分问题涉及是否有任何方法可以限制使用此技术传递给F f的内容。

实现这一点的另一种方法是使用函数指针:

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

这两种方法之间有什么区别吗(除了必须调用它们的方式;即第一种方式用find_if(arg1,arg2,f)调用,第二种方式用find_if<f>(arg1,arg2)调用。

如果有分歧,你能给我描述和解释一下吗?

传递

函数指针比传递我们对其应用(*b)的类型更具限制性。

在课程的情况下,您可以通过

  • 函子类(可能具有状态)为:

    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;
    };
    
  • 或任何函数指针,其中f(*b)是正确的(例如,f可以采用浮点数,而*bint)。

  • 或 lambda (C++11)。