Using std :: for_each by polymorphic method in C ++

When using std :: for_each

class A;
vector<A*> VectorOfAPointers;

std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo));

If we have classes that inherit from A and implement foo (), and we hold the vector of pointers to A, is there a way to call a polymorphic call to foo (), and then explicitly call A :: foo ()? Note. I can not use boost, only the standard STL.

Thanks Gal

+3
source share
1 answer

It works that way.

#include <algorithm>
#include <iostream>
#include <functional>
#include <vector>

struct A {
    virtual void foo() {
        std::cout << "A::foo()" << std::endl;
    }
};
struct B: public A {
    virtual void foo() {
        std::cout << "B::foo()" << std::endl;
    }
};

int main()
{
    std::vector<A*> VectorOfAPointers;
    VectorOfAPointers.push_back(new B());
    std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo));
    return 0;
}

prints

B::foo()

Thus, he does exactly what you want. Make sure keywords are virtualpresent, but easy to forget.

+11
source

All Articles