473,804 Members | 3,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Templated for-loop fantasy

I use the STL collection classes a lot, and frequently find myself
writing something like:

vector<CDataCla ss>::iterator iter=DataClassC ollection.begin ();
vector<CDataCla ss>::iterator iter_end=DataCl assCollection.e nd();
for(;iter!=iter _end;++iter)
{
//doing stuff with iter...
}

I have this fantasy that it ought to be possible to create a template
to replace all of that with something that looks like:

for<CDataClass> (DataClassColle ction) dataiteration;
//the for<> template could have a variety of loop types and data items
(iterators, etceteras)
//defined. A simple case that iterates over each element in the
DataClassCollec tion might
//look like this:
dataiteration.i terate
{
//doing stuff with "dataiteration. iter"
}

And yes, I know about the for_each method. The problem is that
for_each is a bit awkward to use, and I'd like a template construct
which has the capability of operating on a subsequent statement or
block of statements. I'm not aware that such a capabity exists in C++.

Any ideas/suggestions?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 9 '06 #1
13 2237
algorimancer wrote:
I use the STL collection classes a lot, and frequently find myself
writing something like:

vector<CDataCla ss>::iterator iter=DataClassC ollection.begin ();
vector<CDataCla ss>::iterator iter_end=DataCl assCollection.e nd();
for(;iter!=iter _end;++iter)
{
//doing stuff with iter...
}


Have you looked at boost ForEach macro, scheduled to be part of the
boost distro at some stage?

http://boost-consulting.com/vault/in...ory=Algorithms

If the link doesnt work go to http://www.boost.org. Find link to vault
and look in algorithms directory.

cheers
Andy Little

Feb 9 '06 #2

algorimancer wrote:
I use the STL collection classes a lot, and frequently find myself
writing something like:

vector<CDataCla ss>::iterator iter=DataClassC ollection.begin ();
vector<CDataCla ss>::iterator iter_end=DataCl assCollection.e nd();
for(;iter!=iter _end;++iter)
{
//doing stuff with iter...
}


#include <boost/foreach.hpp>

BOOST_FOREACH(C DataClass& v, DataClassCollec tion)
{
// do stuff with v
}
James
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 9 '06 #3
I had not been aware of the boost FOREACH macro, it looks like it could
do the trick. The boost library seems more accessible than the last
time I looked at it, I'll spend some more time there I think.

Thanks :)

Feb 9 '06 #4
algorimancer wrote:
I use the STL collection classes a lot, and frequently find myself
writing something like:

vector<CDataCla ss>::iterator iter=DataClassC ollection.begin ();
vector<CDataCla ss>::iterator iter_end=DataCl assCollection.e nd();
for(;iter!=iter _end;++iter)
{
//doing stuff with iter...
}

I have this fantasy that it ought to be possible to create a template
to replace all of that with something that looks like:

for<CDataClass> (DataClassColle ction) dataiteration;
//the for<> template could have a variety of loop types and data items
(iterators, etceteras)
//defined. A simple case that iterates over each element in the
DataClassCollec tion might
//look like this:
dataiteration.i terate
{
//doing stuff with "dataiteration. iter"
}


You've probably thought of this, but...

template <typename Coll, typename Func>
void iterate(Coll& c, Func f)
{
std::for_each(c .begin(), c.end(), f);
}

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 9 '06 #5

algorimancer wrote:
And yes, I know about the for_each method. The problem is that
for_each is a bit awkward to use, and I'd like a template construct
which has the capability of operating on a subsequent statement or
block of statements. I'm not aware that such a capabity exists in C++.

Any ideas/suggestions?


There is also Boost Lambda and Phoenix that let you do things like:

for_each(begin, end, cout << arg1); // Phoenix version...

I've never used either I just mention it as an idea to look into.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 10 '06 #6
ro**********@gm ail.com wrote:
There is also Boost Lambda and Phoenix that let you do things like:

I wouldn't use these libraries in a production code. For example, I really do not want to
see Boost.Lambda expression in a call stack when I am looking at a core dump of a
production problem. Also, the syntax of any nontrivial Boost.Lambda expression is just
unreadable (as it introduces a new syntax for already existing C++ constructs).
Not to mention that the compiled code is dog slow if inlining is disabled.

--

Valentin Samko - http://www.valentinsamko.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 10 '06 #7
James Hopkin wrote:
#include <boost/foreach.hpp>

BOOST_FOREACH(C DataClass& v, DataClassCollec tion)
{
// do stuff with v
}


This is not included in Boost yet. Actually, it wasn't easy to find the
source code - I found it only here:

http://www.nwcpp.org/Meetings/2004/01.html

There's also this page about the library:

http://www.boost.org/regression-logs...l/foreach.html

but I didn't find the source code there.

BOOST_FOREACH is a bit heavy (see the Portability page), actually, as
most Boost libraries. You can define simple macros for your own needs,
like this:

#define for_vector(T,v, i) \
for ( std::vector<T>: :iterator i=v.begin(); i != v.end(); ++i )

and use it like this:

for_vector( CDataClass, DataClassCollec tion, iter )
{
//doing stuff with iter...
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 10 '06 #8

Ivan Kolev wrote:
James Hopkin wrote:
#include <boost/foreach.hpp>

BOOST_FOREACH(C DataClass& v, DataClassCollec tion)
{
// do stuff with v
}
This is not included in Boost yet.


Thanks for pointing that out. I'd forgotten I'd dug it out of the boost
sandbox and imported it into our company copy of boost.


BOOST_FOREACH is a bit heavy (see the Portability page), actually, as
most Boost libraries.

I have to admit, it does pull in a lot of headers. But if you're using
boost regularly, that won't be noticeable, especially with the commonly
used stuff in a pre-compiled header.

You can define simple macros for your own needs,
like this:

#define for_vector(T,v, i) \
for ( std::vector<T>: :iterator i=v.begin(); i != v.end(); ++i )


Not such a bad idea, although I'd write it:

#define for_vector(T,v, i) \
for (std::vector<T> ::iterator i=v.begin(), _end = v.end(); i != _end;
++i)
Note that a major benefit of BOOST_FOREACH is that it works with any
container, pairs of iterators (e.g. a return value from equal_range)
and built-in arrays.
James
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 10 '06 #9
> I have to admit, it does pull in a lot of headers. But if you're using
boost regularly, that won't be noticeable, especially with the commonly
used stuff in a pre-compiled header.
Yes, it depends on whether you're using Boost or not. Once you start,
you get everything new in Boost sort of "for free".
Not such a bad idea, although I'd write it:

#define for_vector(T,v, i) \
for (std::vector<T> ::iterator i=v.begin(), _end = v.end(); i != _end;
++i)
Indeed. Though I guess vector::end() should be simple enough to be
inlined, this could be useful for other containers.
Note that a major benefit of BOOST_FOREACH is that it works with any
container, pairs of iterators (e.g. a return value from equal_range)
and built-in arrays.


BOOST_FOREACH is impressive. By coincidence, I was working these days
on something similar, trying to create something like a generic
iterator class, but of course nothing can beat the Boost libraries. So
the news about BOOST_FOREACH was very timely for me - thank you :).
Although our project is not "Boost-enabled" yet, it's good to know what
can be done, and also what can we expect of the next standard. Having
foreach included in C++0x would be great.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Feb 11 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6578
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? Here's what I'm generally trying to achieve: I'm building (trying to anyway) a serialization library. Here's my design:
1
1872
by: Rich | last post by:
Hi, I have a query regarding VC6 and its handling of templated copy constructors. Here goes: Take a look at the following code sample... template<class _Ty, size_t t_uiSize = 10 > class my_template
2
1918
by: ferdinand.stefanus | last post by:
Hi, I have some questions regarding templated class constructor: #include <iostream> using namespace std; template<typename T> class Foo { public:
4
1869
by: Lionel B | last post by:
Greetings, The following code: <code> template<typename T> class A { protected:
6
1316
by: Alex | last post by:
I have been loving the templated datacolumns of the datagrid. I have stumbled onto a problem though that is beyond by knowledge and I was hoping someone here could jumpstart me. My templated columns work find as long as I pass in a dataset but if I pass in a collection of objects then they won't work unless I can cast the correct object and then fill in the column with the object. My current code looks like this: public void...
0
2350
by: Mike | last post by:
Hi. I can't figure out why a button's click event is not firing in a templated control I've created (first time I've tried creating one). Please can someone help? On a point of lesser importance, how can I get the designer to realise that my control can contain markup? This is all ASP.Net v 2.0 This is my default.aspx: Below is the source of three files: Default.aspx, Default.aspx.cs and
2
1690
by: mattjgalloway | last post by:
I'm having some problems with a templated member function of a templated class. Unfortunately I can't replicate it with a simple example so I know something odd must be going on!!! Basically it's like this... I have a few classes all templated by one type. Inside one of the classes is a templated member function. When I try to use this templated function in another class, the compiler complains with: error: expected primary-expression...
7
1731
by: Claudius | last post by:
Hello, in my class TopTen I need to define three constructors while only the last one, the most general in terms of templates, should be sufficient in my opinion: template <typename Tnum, short Trank, bool Tcont> TopTen<Tnum,Trank,Tcont>::TopTen( const TopTen<Tnum,Trank,Tcont& tten );
2
2939
by: domehead100 | last post by:
I have a templated class, CDerived: template <typename TValue, typename TDraw, typename TEdit ...> class CDerived : public CBase { TValue m_Value public: TValue& GetValue() const {
2
2291
card
by: card | last post by:
Hi everyone, I have a question about referencing a nested class contained within a templated class. Of course the best way to show you is by example. Here's my templated classes: #include <stack> template <class T> class A { public:
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10561
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.