简体   繁体   English

如何在for_each中使用dynamic_cast

[英]How to use dynamic_cast with for_each

I have the following code: 我有以下代码:

vector<C1*>::iterator itr = vec.begin();
for (; itr != vec.end(); ++itr) {
  C2 *c = dynamic_cast<C2*>(*itr);
  c->f();
}

I am wondering if I could use one-line for_each to replace it. 我想知道我是否可以使用one-line for_each来替换它。 I tried the following: 我尝试了以下方法:

for_each(vec.begin(), vec.end(), bind2nd(mem_fun(&C2::f), dynamic_cast<C2*>));

But I get a compile error, 但是我收到编译错误,

expected unqualified-id before 'dynamic_cast'

What should be the right then? 什么应该是正确的呢?

[EDIT] I cannot use c++11. [编辑]我不能使用c ++ 11。 Looks like I have to define an extra functor, sigh. 看起来我必须定义一个额外的仿函数,叹息。

For some questionings about the code itself: C1 and C2 are 2 pure interfaces; 关于代码本身的一些问题:C1和C2是2个纯接口; f() is only available as C2's API. f()仅作为C2的API提供。 The vector "vec" has a list of objects which have both C1 and C2 interfaces, but they are passed to this piece of code as vector of C1*. 向量“vec”有一个具有C1和C2接口的对象列表,但它们作为C1 *的向量传递给这段代码。

Under C++11, instead of doing all this bind stuff, I would use a lambda : 在C ++ 11下,我会使用lambda而不是做所有这些bind东西:

for_each (vec.begin(), vec.end(), [] (C1* c1) 
{
  C2* c2 = dynamic_cast <C2*> (c1);
  if (c2)
  { 
    c2->f();
  }
});

If using C++11 isn't possible, or if for some other reason you shy away from this, then I would construct a functor to wrap this in: 如果使用C ++ 11是不可能的,或者由于某些其他原因你回避这个,那么我将构造一个函子来包装它:

struct call_f
:
  public std::unary_function <C1*, void>
{
  void operator () (C1* c1) const
  {
    C2* c2 = dynamic_cast <C2*> (c1);
    if (c2)
    {
      c2->f();
    }
  }
};

// ...

for_each (vec.begin(), vec.end(), call_f());

dynamic_cast<...>() may look like a function but it isn't one. dynamic_cast<...>()可能看起来像一个函数,但它不是一个函数。 You could use something like this: 你可以使用这样的东西:

template <typename T>
struct dynamic_cast_fun {
    template <typename F>
    T* operator()(F* from) const {
        return dynamic_cast<T*>(F* from);
    }
};

(possibly with some extra overloads to deal with the constness of the argument). (可能有一些额外的重载来处理参数的常量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM