Suppose I have two classes B and D. I can have several types of containers of pointers of B and D. For example
std::vector<B *> VecPB;
std::list<D *> ListPD;
Assume also that B and D are somehow related in the sense that they have some common memmber functions (to_str, is_valid, is_ok, ..., etc)
Say there is a member function to_str that can be called in each element of B or D to get the string representation of B or D. There is also a another member function that can be applied to B or D is_valid(). So I can say for example VecPB.front()->is_valid()
What I want is to be able to write function that prints all the valid elements in a container of type B or D.
For example, I can write:
void display_ValidB(const std::vector<B *> & v) {
for(std::vector<B *>::const_iterator it = v.begin(); it != v.end(); ++it)
{
if((*it)->is_valid())
std::cout << (*it)->to_str() << std::endl;
}
}
I can abstract this one more level and use
template<typename T>
void display_valid<const std::vector<T *> & v) {
for(std::vector<T *>::const_iterator it = v.begin(); it != v.end(); ++it)
{
if((*it)->is_valid())
std::cout << (*it)->to_str() << std::endl;
}
}
But now my problem is: Is there a way that I don't have to write a template function for each type of container? I would not want to write a different template function to vector, set, list, etc....
How to generalize this so that the display_function could take a lambda function as an argument so I could write
display_function<D>(ListPD, [](const D & d) {return !d->is_ok();});
or, something like
display_function<D>(listpd.begin(), listpd.end(), [](const d & d) {return !d->is_ok();});
I can use up to C++11 but not C++14.
Aucun commentaire:
Enregistrer un commentaire