我必须使用boost :: bind来创建多态“转换”功能吗?

时间:2015-03-08 22:03:55

标签: c++ boost c++03 mem-fun

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

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与bind2nd一起工作我需要传入参数t,所以我想知道它是否可行..?

1 个答案:

答案 0 :(得分: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