我经常听到很多关于c++中的函子。谁能给我一个概述,他们是什么,在什么情况下他们会有用?


当前回答

在gtkmm中使用函子将一些GUI按钮连接到实际的c++函数或方法。


如果你使用pthread库使你的应用程序多线程,Functors可以帮助你。 要启动一个线程,pthread_create(..)的参数之一是要在自己的线程上执行的函数指针。 但有一个不便之处。这个指针不能是指向方法的指针,除非它是一个静态方法,或者除非你指定了它的类,比如class::method。还有一件事,你方法的接口只能是:

void* method(void* something)

因此,如果不做一些额外的事情,你就不能(以一种简单明显的方式)在线程中运行你的类中的方法。

在c++中处理线程的一个很好的方法是创建你自己的Thread类。如果你想运行MyClass类的方法,我所做的是,把那些方法转换成Functor派生类。

同样,Thread类有这样的方法: 静态void* startThread(void*参数) 指向该方法的指针将用作调用pthread_create(..)的参数。startThread(..)在arg中应该接收到的是一个void*类型的引用,它指向任何Functor派生类的堆中的实例,在执行时将被强制转换回Functor*,然后调用它的run()方法。

其他回答

函子也可以用来模拟在函数中定义局部函数。参考这个问题和另一个问题。

但是局部函子不能访问外部的自动变量。lambda (c++ 11)函数是一个更好的解决方案。

将函数作为函子实现的一个很大的优点是,它们可以在调用之间维护和重用状态。例如,许多动态规划算法,如用于计算字符串之间的Levenshtein距离的Wagner-Fischer算法,都是通过填充一个大的结果表来工作的。每次调用函数时分配这个表的效率非常低,因此将函数作为函子实现并将表作为成员变量可以极大地提高性能。

下面是一个将Wagner-Fischer算法实现为函子的示例。注意表是如何在构造函数中分配,然后在operator()中重用的,并根据需要调整大小。

#include <string>
#include <vector>
#include <algorithm>

template <typename T>
T min3(const T& a, const T& b, const T& c)
{
   return std::min(std::min(a, b), c);
}

class levenshtein_distance 
{
    mutable std::vector<std::vector<unsigned int> > matrix_;

public:
    explicit levenshtein_distance(size_t initial_size = 8)
        : matrix_(initial_size, std::vector<unsigned int>(initial_size))
    {
    }

    unsigned int operator()(const std::string& s, const std::string& t) const
    {
        const size_t m = s.size();
        const size_t n = t.size();
        // The distance between a string and the empty string is the string's length
        if (m == 0) {
            return n;
        }
        if (n == 0) {
            return m;
        }
        // Size the matrix as necessary
        if (matrix_.size() < m + 1) {
            matrix_.resize(m + 1, matrix_[0]);
        }
        if (matrix_[0].size() < n + 1) {
            for (auto& mat : matrix_) {
                mat.resize(n + 1);
            }
        }
        // The top row and left column are prefixes that can be reached by
        // insertions and deletions alone
        unsigned int i, j;
        for (i = 1;  i <= m; ++i) {
            matrix_[i][0] = i;
        }
        for (j = 1; j <= n; ++j) {
            matrix_[0][j] = j;
        }
        // Fill in the rest of the matrix
        for (j = 1; j <= n; ++j) {
            for (i = 1; i <= m; ++i) {
                unsigned int substitution_cost = s[i - 1] == t[j - 1] ? 0 : 1;
                matrix_[i][j] =
                    min3(matrix_[i - 1][j] + 1,                 // Deletion
                    matrix_[i][j - 1] + 1,                      // Insertion
                    matrix_[i - 1][j - 1] + substitution_cost); // Substitution
            }
        }
        return matrix_[m][n];
    }
};

就像其他人提到的,函子是一个像函数一样工作的对象,即它重载函数调用操作符。

函子通常用于STL算法。它们很有用,因为它们可以在函数调用之前和之间保持状态,就像函数语言中的闭包一样。例如,你可以定义一个MultiplyBy函子,将它的参数乘以一个指定的量:

class MultiplyBy {
private:
    int factor;

public:
    MultiplyBy(int x) : factor(x) {
    }

    int operator () (int other) const {
        return factor * other;
    }
};

然后你可以传递一个MultiplyBy对象给一个像std::transform:这样的算法:

int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}

函子相对于指向函数的指针的另一个优点是可以在更多情况下内联调用。如果你将一个函数指针传递给transform,除非该调用被内联,并且编译器知道你总是将同一个函数传递给它,否则它不能通过指针内联调用。

早在c++出现之前,“functor”这个名字就已经在范畴理论中传统地使用了。这与c++中函子的概念无关。最好使用name function object,而不是c++中所谓的“functor”。这就是其他编程语言调用类似结构的方式。

用于代替普通函数:

特点:

函数对象可以有状态 函数对象适合OOP(它的行为和其他对象一样)。

缺点:

给程序带来了更多的复杂性。


用于代替函数指针:

特点:

函数对象通常可以内联

缺点:

函数对象不能在运行时与其他函数对象类型交换(至少除非它扩展了一些基类,因此会产生一些开销)


用于代替虚函数:

特点:

函数对象(非虚拟)不需要虚表和运行时调度,因此在大多数情况下更有效

缺点:

函数对象不能在运行时与其他函数对象类型交换(至少除非它扩展了一些基类,因此会产生一些开销)

函子是一种高阶函数,它将函数应用于参数化(即模板化)类型。它是映射高阶函数的推广。例如,我们可以像这样为std::vector定义一个函子:

template<class F, class T, class U=decltype(std::declval<F>()(std::declval<T>()))>
std::vector<U> fmap(F f, const std::vector<T>& vec)
{
    std::vector<U> result;
    std::transform(vec.begin(), vec.end(), std::back_inserter(result), f);
    return result;
}

这个函数接受一个std::vector<T>,并在给定一个接受T并返回U的函数F时返回std::vector<U>。一个函子不一定要在容器类型上定义,它也可以为任何模板类型定义,包括std::shared_ptr:

template<class F, class T, class U=decltype(std::declval<F>()(std::declval<T>()))>
std::shared_ptr<U> fmap(F f, const std::shared_ptr<T>& p)
{
    if (p == nullptr) return nullptr;
    else return std::shared_ptr<U>(new U(f(*p)));
}

下面是一个将类型转换为double类型的简单示例:

double to_double(int x)
{
    return x;
}

std::shared_ptr<int> i(new int(3));
std::shared_ptr<double> d = fmap(to_double, i);

std::vector<int> is = { 1, 2, 3 };
std::vector<double> ds = fmap(to_double, is);

函子应该遵循两条定律。第一个是恒等定律,它指出,如果函子给定了恒等函数,它应该与将恒等函数应用于类型相同,即fmap(identity, x)应该与identity(x)相同:

struct identity_f
{
    template<class T>
    T operator()(T x) const
    {
        return x;
    }
};
identity_f identity = {};

std::vector<int> is = { 1, 2, 3 };
// These two statements should be equivalent.
// is1 should equal is2
std::vector<int> is1 = fmap(identity, is);
std::vector<int> is2 = identity(is);

下一个定律是组合定律,它指出,如果函子被赋予两个函数的组合,它应该与将函子应用于第一个函数,然后再应用于第二个函数相同。因此,fmap(std::bind(f, std::bind(g, _1)), x)应该与fmap(f, fmap(g, x))相同:

double to_double(int x)
{
    return x;
}

struct foo
{
    double x;
};

foo to_foo(double x)
{
    foo r;
    r.x = x;
    return r;
}

std::vector<int> is = { 1, 2, 3 };
// These two statements should be equivalent.
// is1 should equal is2
std::vector<foo> is1 = fmap(std::bind(to_foo, std::bind(to_double, _1)), is);
std::vector<foo> is2 = fmap(to_foo, fmap(to_double, is));