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 can use single line for_each to replace it. I tried the following:

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

But I get a compilation error,

 expected unqualified-id before 'dynamic_cast' 

What should be right?

[EDIT] I can't use C ++ 11. It looks like I should define an extra functor, sigh.

For some questions about the code itself: C1 and C2 - 2 clean interfaces; The f () function is only available as a C2 API. The "vec" vector has a list of objects that have both C1 and C2 interfaces, but they are passed to this code fragment as C1 * vector.

+7
c ++ foreach dynamic-cast
source share
2 answers

In C ++ 11, instead of executing all this bind tag, I would use lambda :

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

If using C ++ 11 is not possible, or if for some other reason you are avoiding this, then I would build a functor to wrap this in:

 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()); 
+6
source share

dynamic_cast<...>() may look like a function, but this is not one. You can 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); } }; 

(perhaps with some extra overloads to deal with the argument constant).

+1
source share

All Articles