在C++ 03中将成员函数传递给for_each(没有提升,没有c ++ 11)

Ali*_*Ali 5 c++ stl c++03

下面的"解决方案"编译,但它不是我想要的.我想传递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;
}
Run Code Online (Sandbox Code Playgroud)

tem*_*def 12

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

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

调用mem_fun创建一个新的函数对象,它接受两个参数 - 一个Car*充当接收器和a Wheel,然后调用put第一个参数作为接收器,第二个参数作为参数.bind1st然后调用将接收器对象锁定为该函数的第一个参数.

但是,我认为您需要对此代码进行一次小的更改才能使其正常工作.该bind1st适配器不与通过const引用取它们的参数的功能发挥好,所以你可能需要改变put,这样它需要Wheel通过值而不是引用.