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

时间:2009-05-09 00:36:50

标签: c++ stl boost

我有:

class T {};

class S: public T {};

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

transform(v.begin(), v.end(), dynamic_cast_iterator<S*>(w.begin()));

但是,当然,dynamic_cast_iterator不存在。

2 个答案:

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

答案 1 :(得分:4)

您可以使用boost::transform_iterator为自己编写dynamic_cast_iterator。它必须在调用transform时应用于源迭代器,但不是目标迭代器。


#include <algorithm>
#include <vector>
#include <boost/iterator/transform_iterator.hpp>

//First define a unary functor object that dynamic_casts.
//(This is easier than using boost::lambda, because writing the type of
//boost::lambda::ll_dynamic_cast is fairly tricky.)
template <typename Target>
struct dynamic_caster
{
    typedef Target result_type;
    template <typename Source>
    Target operator()(Source s) const
    {
         return dynamic_cast<Target>(s);
    }
};

template <typename Target, typename Iterator>
boost::transform_iterator<dynamic_caster<Target>, Iterator>
make_dynamic_cast_iterator(Iterator it)
{
    return boost::make_transform_iterator(it, dynamic_caster<Target>());
}

//Then use like this:
int main()
{
    std::vector<T*> v; 
    //(Populate v)


    std::vector<S*> w;
    std::transform(make_dynamic_cast_iterator<S *>(v.begin()), 
              make_dynamic_cast_iterator<S *>(v.end()), 
              w.begin());
    //Or initialise a vector from v
    std::vector<S*> x(
        make_dynamic_cast_iterator<S *>(v.begin()), 
        make_dynamic_cast_iterator<S *>(v.end()));

}