The conditions are:
// A hierarchy
struct Base {
virtual void everyone_has_this() = 0;
};
struct DA : Base {
void everyone_has_this() override {...}
};
struct DB : Base {
void everyone_has_this() override {...}
void only_db_has_this() {...}
};
// And some vectors
vector<DA> das (3);
vector<DB> dbs (2);
I'd love to be able to use something like:
// Foreach all of them in one loop
for(Base& o : view_as_one<Base>(das, dbs)) {
o.everyone_has_this();
}
// Or just several types of them
for(DB& o : dbs) {
db.only_db_has_this();
}
The question is: is it possible?
If not, what are the other ways to one loop, instead of for each container?
Important is, I don't want to get rid of the segregation and storage contigiousness.
A dynamic_cast would work, if I used a single base pointer container, but it would involve checking for the type on every iteration, and the goal is to store all the objects in contigious storages.
Edit: Alternative solution if boost is not an option or view is not enough
While I do love m.s.'s solution, because he implemented exactly the interface I asked for, I found that this interface I wanted, is not actually that flexible (can't use erase-remove).
So here's a different approach:
for_each_in_tuple(std::tie(das, dbs), [](auto& cont){
for(auto& obj : cont) {
// do what you want
}
// or even
cont.erase(std::remove_if(begin(cont), end(cont), [](auto& obj) {
// also do what you want
}, end(cont));
});
- (-) Not as pretty
- (+) The iterator doesn't have to check which range it belongs to (faster)
- (+) It works even without virtual methods (because
auto&
). - (+) Dependency only on
<tuple>
=> no boost & compiles faster. - (+) Not as restricted (e.g. can use erase-remove)
- (?) Not sure, but looks like msvc2015 can compile too.
Note:
There are a plentiful of for_each tuple algorithms. I took this one:
http://pastebin.com/6e8gmZZA