does STL has a binder or an adaptor for type-casting?

D

Diego Martins

Let's say I have a vector of pointers of Base
vector<Base *> vec;

Now, someone assured me all elements of the vector are of dynamic type
Derived *.

I want to use for_each or other STL algorithms in this container using
Derived members.

My current workaround is presented as follows:

void KludgeFunction(Base * elem) {
static_cast<Derived *>(elem)->myDerivedOperation();
}
....
for_each(vec.begin(),vec.end(),KludgeFunction);


We know if vec was vector<Derived *>, we can do it more simply by:

for_each(vec.begin(),vec.end(),mem_fun(&Derived::myDerivedOperation));


Do you how can I build something to avoid writing the KludgeFunction?
- an interator adaptor?
- a binder?

any ideas?

Diego Martins
HP
 
V

Victor Bazarov

Diego said:
Let's say I have a vector of pointers of Base
vector<Base *> vec;

Now, someone assured me all elements of the vector are of dynamic type
Derived *.

I want to use for_each or other STL algorithms in this container using
Derived members.

My current workaround is presented as follows:

void KludgeFunction(Base * elem) {
static_cast<Derived *>(elem)->myDerivedOperation();
}
...
for_each(vec.begin(),vec.end(),KludgeFunction);


We know if vec was vector<Derived *>, we can do it more simply by:

for_each(vec.begin(),vec.end(),mem_fun(&Derived::myDerivedOperation));


Do you how can I build something to avoid writing the KludgeFunction?
- an interator adaptor?

What's an "interator"? Do you mean "iterator"?
- a binder?

any ideas?

What you described should be implemented using _polymorphic_ abilities
of the classes. Then there would be no need for "kludges" or "adapters".

V
 
D

Daniel T.

"Diego Martins said:
Let's say I have a vector of pointers of Base
vector<Base *> vec;

Now, someone assured me all elements of the vector are of dynamic type
Derived *.

I want to use for_each or other STL algorithms in this container using
Derived members.

My current workaround is presented as follows:

void KludgeFunction(Base * elem) {
static_cast<Derived *>(elem)->myDerivedOperation();
}
...
for_each(vec.begin(),vec.end(),KludgeFunction);


We know if vec was vector<Derived *>, we can do it more simply by:

for_each(vec.begin(),vec.end(),mem_fun(&Derived::myDerivedOperation));


Do you how can I build something to avoid writing the KludgeFunction?
- an interator adaptor?
- a binder?

any ideas?

The simplest fix would be to change your vector to 'vector<Derived*>'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top