在C ++ 03中将成员函数传递给for_each(没有boost,没有c ++ 11) [英] Passing a member function to for_each in C++03 (no boost, no c++11)

查看:91
本文介绍了在C ++ 03中将成员函数传递给for_each(没有boost,没有c ++ 11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The "solution" below compiles but it is not what I want. I would like to pass the put member function to for_each and not *this. Using boost is NOT an option. Can this be solved within 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;
}


推荐答案

mem_fun bind1st 模板的组合:

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

调用 mem_fun 创建一个新的函数对象,它接受两个参数 - Car * 作为接收者, Wheel 然后调用 put ,第一个参数作为接收者,第二个参数作为参数。调用 bind1st 然后锁定接收器对象作为此函数的第一个参数。

The call to mem_fun creates a new function object that takes in two arguments - a Car* to act as the receiver and a Wheel, then calls put with the first parameter as the receiver and the second parameter as the argument. Calling bind1st then locks the receiver object as first parameter of this function in place.

需要对此代码进行一个小的更改才能使其工作。 bind1st 适配器对于通过const引用接受其参数的函数不适用,因此您可能需要更改 put ,以便它通过值而不是引用获取 Wheel

However, I think you will need to make one small change to this code to get it to work. The bind1st adapter doesn't play well with functions that take their arguments by const reference, so you might need to change put so that it takes a Wheel by value rather than by reference.

这篇关于在C ++ 03中将成员函数传递给for_each(没有boost,没有c ++ 11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆