5

下面的“解决方案”可以编译,但这不是我想要的。我想将put成员函数传递给for_each而不是*this。使用 boost不是一种选择。这可以在 C++03 中解决吗?

#include <algorithm>
#include <functional>
#include <vector>
using namespace std;

class Wheel { };

class Car {

public:

    void process(const vector<Wheel>& wheel) {

        for_each(wheel.begin(), wheel.end(), *this);
    }

    void operator()(const Wheel& w) { put(w); }

private:

    void put(const Wheel& w) { }
};

int main() {

    vector<Wheel> w(4);

    Car c;

    c.process(w);

    return 0;
}
4

3 回答 3

12

是的,它可以,使用mem_funbind1st模板的组合:

void process(const vector<Wheel>& wheel) {
    for_each(wheel.begin(), wheel.end(), bind1st(mem_fun(&Car::put), this));
}

调用mem_fun创建一个新的函数对象,它接受两个参数 - aCar*作为接收者和 a Wheel,然后put使用第一个参数作为接收者和第二个参数作为参数进行调用。然后调用bind1st将接收器对象锁定为该函数的第一个参数。

但是,我认为您需要对该代码进行一些小的更改才能使其正常工作。bind1st适配器不能很好地与通过 const 引用获取参数的函数配合使用,因此您可能需要进行更改put,以使其采用Wheel值而不是引用。

于 2011-01-09T23:26:33.430 回答
3

您可以使用 mem_fun_ref:请参见此处

mem_fun_ref应该在你有对象向量的情况下工作:

for_each(wheel.begin(), wheel.end(), mem_fun_ref(&Wheel::put));

请注意,上面的示例更改put为 Wheel 而不是 Car 的成员。它应该让您了解如何使用它。

mem_fun如果您有指向对象的指针向量,请使用

于 2011-01-09T23:41:39.533 回答
1

当然——你可以写你自己的 boost::mem_func 等价物。TR1 也有一个。如果您想要增加参数数量,这有点重复,但在概念上并不难。

template<typename T, typename mem_func_type> struct mem_func_internal;
template<typename T, typename Ret> struct mem_func_internal<T, Ret (T::*)()> {
    typedef Ret(T::* functype)();
    T* obj;
    functype func;
    Ret operator()() {
        return obj->*func();
    }
};
template<typename T, typename Ret, typename ArgType1> struct mem_func_internal<T, Ret (T::*)(ArgType1) {
    typedef Ret(T::* functype)();
    T* obj;
    functype func;
    Ret operator()(ArgType1 arg) {
        return obj->*func(arg);
    }
 }
template<typename T, typename mem_func_type> struct mem_func : public mem_func_internal<T, mem_func_type> {
    mem_func(T* object, mem_func_type mem_func)
        : obj(object)
        , func(mem_func) {}
};
template<typename T, typename mem_func_type> mem_func<T, mem_func_type> bind_mem_func(T* object, mem_func_type func) {
    return mem_func<T, mem_func_type>(object, func);
}
// Usage
std::for_each(wheel.begin(), wheel.end(), bind_mem_func(this, &Car::put));

自从我写这样的代码以来已经有一段时间了,所以它可能有点不对劲。但这就是它的要点。如果不使用 lambda,很难编写一个使用示例。

于 2011-01-09T23:28:08.783 回答