1

我正在尝试使用指定的参数对向量中的每个对象调用成员函数,并且我希望调用是多态的。我相信下面显示的函数 vstuff 可以实现这一点。但是可以修改 vstuff 以在不使用 boost::bind 的情况下采用向量<shared_ptr <Base>>?

class Base{
            virtual double stuff(double t);
           }
//and some derived classes overriding stuff
//then in some code 
vector<double> vstuff(double t, vector<Base*> things)
{
vector<double> vals;
vals.resize(things.size());
transform(things.begin(), things.end(), vals.begin(), std::bind2nd(std::mem_fun(&Base::stuff),t));
return vals;
}

我知道 shared_ptr 需要 mem_fn 而不是 mem_fun ,但是我没有成功让 mem_fn 与我需要传入参数 t 的 bind2nd 一起工作,所以我想知道它是否可行..?

4

1 回答 1

0

您也可以使用std::bind(或 lambdas):

Live On Coliru

#include <algorithm>
#include <vector>
#include <memory>

struct Base {
    virtual double stuff(double) { return 0; }
};

struct Threes : Base {
    virtual double stuff(double) { return 3; }
};

struct Sevens : Base {
    virtual double stuff(double) { return 7; }
};

std::vector<double> vstuff(double t, std::vector<std::shared_ptr<Base> > things)
{
    std::vector<double> vals;
    vals.resize(things.size());
    transform(things.begin(), things.end(), vals.begin(), std::bind(&Base::stuff, std::placeholders::_1, t));
    return vals;
}

#include <iostream>

int main() {
    for (double v : vstuff(42, {
                std::make_shared<Sevens>(),
                std::make_shared<Sevens>(),
                std::make_shared<Sevens>(),
                std::make_shared<Threes>(),
                std::make_shared<Sevens>(),
                std::make_shared<Threes>(),
                std::make_shared<Sevens>(),
                std::make_shared<Sevens>(),
                std::make_shared<Threes>(),
                std::make_shared<Sevens>(),
            }))
    {
        std::cout << v << " ";
    }
}

印刷

7 7 7 3 7 3 7 7 3 7 
于 2015-03-09T01:22:15.283 回答