如何在指针向量之间动态转换?

Nei*_*l G 3 c++ boost stl

我有:

class T {};

class S: public T {};

vector<T*> v;
vector<S*> w;

transform(v.begin(), v.end(), dynamic_cast_iterator<S*>(w.begin()));
Run Code Online (Sandbox Code Playgroud)

但是,当然,dynamic_cast_iterator不存在.

Joh*_*itb 12

这是一个解决方案(使用boost lambda):

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/casts.hpp>
#include <algorithm>
#include <iterator>
#include <iostream>

namespace bll = boost::lambda;

struct A { virtual ~A() { } };
struct B : A { void f() { std::cout << "hello, world" << std::endl; } };

int main() {
    std::vector<A*> a; a.push_back(new B);
    std::vector<B*> b;
    std::transform(a.begin(), a.end(), std::back_inserter(b), 
                   bll::ll_dynamic_cast<B*>(bll::_1));
    b[0]->f();
    delete a[0];
}
Run Code Online (Sandbox Code Playgroud)