• Advertisement
Sign in to follow this  

Evil?

This topic is 4937 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

#define FOR_EACH(OBJECT, CONTAINER, CONTAINER_TYPE) for (CONTAINER_TYPE::iterator OBJECT = CONTAINER.begin(); OBJECT != CONTAINER.end(); ++OBJECT)

It doesn't work with strings though. Would this be classified as evil? I would think that this is one good use of #define, as this can't be done with a function (is boost's for_each as powerful as a for-loop?), and it shows your intent with much less code.

Share this post


Link to post
Share on other sites
Advertisement
Eh. You could do it with a template function. It may be a bit more verbose, but using a macro is asking for trouble. STL has a for_each( ) template function.

Share this post


Link to post
Share on other sites
Quote:
Original post by microdot
Eh. You could do it with a template function. It may be a bit more verbose, but using a macro is asking for trouble. STL has a for_each( ) template function.


With template functions, you need function pointers. You can't use it as you would a for_each in C#.

Share this post


Link to post
Share on other sites
Quote:
Original post by thedevdan
With template functions, you need function pointers.


No you don't, for_each doesn't have a parameter of type pointer to function, it has a parameter in which you can pass a free function, member function virtual & non-virtual, functional objects (functors) but it doesn't use function pointer as it's parameter.

Share this post


Link to post
Share on other sites
Quote:
Original post by snk_kid
Quote:
Original post by thedevdan
With template functions, you need function pointers.


No you don't, for_each doesn't have a parameter of type pointer to function, it has a parameter in which you can pass a free function, member function virtual & non-virtual, functional objects (functors) but it doesn't use function pointer as it's parameter.


Member function pointers need to be bound with mem_fun_ref etc, IIRC.

Share this post


Link to post
Share on other sites
C++ doesn't have lambdas. Therefore, it doesn't have convenient for_each. Live with it, don't fight against it. Or, if you do fight against it, fight against it with something powerful.

Share this post


Link to post
Share on other sites
If you really want to live on the edge, try this.

std::vector<int> numbers = ...;
int q;
FOR_EACH(int& i, numbers) {
i=q++;
if (q > 10) break; // yes, this works
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement